Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the output of the following 'C' language statements?

#include\(\lt\)stdio.h\(\gt\)
int main(){
int a=10,b=20,*p1=&a,*p2=&b;
printf("Before : **p1=%d **p2=%d",*p1,*p2);
*p1=*p1+*p2;
*p2=*p1-*p2;
*p1=*p1-*p2;
printf("\nAfter : **p1=%d **p2=%d",*p1,*p2);
return 0;
}

  • A.Before : **p1=10 **p2=20 / After : **p1=20 **p2=10
  • B.Before : **p1=20 **p2=10 / After : **p1=10 **p2=20
  • C.Before : p1=10 p2=20 / After : p1=20 p2=10
  • D.Before : *p1=10 *p2=20 / After : *p1=20 *p2=20

Answer: A

The output is Before : **p1=10 **p2=20 and then After : **p1=20 **p2=10. The pointers p1 and p2 point to a and b, so the three statements swap the values without a temporary variable. \[ *p1 = 10 + 20 = 30 \] \[ *p2 = 30 - 20 = 10 \] \[ *p1 = 30 - 10 = 20 \] The strings '**p1=' and '**p2=' are printed as plain text. The second option reverses the values, the third drops the asterisks that the format string prints, and the fourth gives the wrong second value.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.