Understand the comma

int main() { int a = (1,2,3); int b = (++a, ++a, ++a); int c= (b++, b++, b++); printf("%d %d %d", a,b,c); } 

I'm starting to program. I do not understand how this program shows me the output of 6 9 8 .

+6
source share
3 answers

, used in all three ads

 int a = (1,2,3); int b = (++a, ++a, ++a); int c = (b++, b++, b++); 

comma It evaluates the first operand 1 and discards it, then calculates the second operand and returns its value. Hence,

 int a = ((1,2), 3); // a is initialized with 3. int b = ((++a, ++a), ++a); // b is initialized with 4+1+1 = 6. // a is 6 by the end of the statement int c = ((b++, b++), b++); // c is initialized with 6+1+1 = 8 // b is 9 by the end of the statement. 

1 The evaluation order is guaranteed from left to right in the case of a comma.

+8
source

The code is by no means good, and no one in their right mind would ever write it. You should not waste time looking at such code, but I will give an explanation anyway.

The comma operator means "do the left, discard any result, do the right and return the result." Putting parts in parentheses does not affect functionality.

More clearly written code:

 int a, b, c; a = 3; // 1 and 2 have no meaning whatsoever a++; a++; a++; b = a; b++; b++; c = b; b++; 

The operators before and after the increment have a difference in how they act and what causes the difference in the values โ€‹โ€‹of b and c.

+5
source

I'm starting to program. I do not understand how this program shows output

Just familiarize yourself with commas and prefix, postfix .

according to the rules provided in the links provided to you

 int a = (1,2,3); // a is initialized with 3 last argument . int b = (++a, ++a, ++a); // a is incremented three time so becomes 6 and b initilized with 6 . int c = (b++, b++, b++); // b incremented two times becomes 8 and c initialized with 8. // b incremented once more time becomes 9 
+1
source

All Articles