-3

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.

Himanshu Aggarwal
  • 1,803
  • 2
  • 24
  • 36

2 Answers2

2

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;
}
Dapu
  • 195
  • 1
  • 3
  • 13
1

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.

Deepu
  • 7,592
  • 4
  • 25
  • 47
  • i have implemented this program on Turbo C++ and it worked perfectly there. I know the way of using unary operator is incorrect but its just a question I encountered somewhere. – Himanshu Aggarwal Apr 19 '13 at 06:19