Search code examples
cintoperatorsassignment-operatorpostfix-operator

explanation for the code snippet in C


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.


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;
    }