Question

I came across this code snippet somewhere but cannot understand how does it works:

#include"stdio.h"

int main() {
  int j = 1;
  + j += + j += + j++;
  printf("%d",j);
  return 0;
}

Output:

6

Please explain the working of this code snippet.

Was it helpful?

Solution

i hope you will understand if i write the same snippet other way explaining it

just note my point + variable is nothing but a positive variable and - variable is negative

now look at your snippet

#include"stdio.h"

int main() {
int j = 1;
+ j += + j++;// i.e "j+=j++;" which is "j=j+j; j= j+1;"
//now j = j+j "1+1" "j=2" and post increment then j=j+1 "2+1" "j=3"
+j+=+j;//which is j+=j or j=j+j
//hence j=3+3 i.e 6
printf("%d",j);//j=6
return 0;
}

OTHER TIPS

Your program will not compile as you are not providing an lvalue for assignment.

The following error message is shown by GCC,

lvalue required as left operand of assignment

In your program you have used short hand assignment operator,

For example consider the code,

a+=b;

means,

a=a+b;

But the way you used them is incorrect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top