I can write the code if(1) x++, y++;
instead of if(1) {x++; y++;}
, but in some cases it does not work (see below). It would be nice if you tell me about this.
int x = 5, y = 10; if (x == 5) x++, y++; // It works if (x == 5) x++, return 0; // It shows an error
The same applies to for
loops:
for (int i = 0; i < 1; i++) y++, y += 5; // It works for (int i = 0; i < 1; i++) y++, break; // Does not work
The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.
The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.
It is comma operator.
The comma operator will always yield the last value in the comma separated list. Basically it's a binary operator that evaluates the left hand value but discards it, then evaluates the right hand value and returns it. If you chain multiple of these they will eventually yield the last value in the chain.
That's because return
and break
are statements, not expressions. As such, you cannot use it in another expression in any way. if
and the others are similarly also statements.
What you can do however is rewrite your expression (for return
) so that it's not nested in an expression - not that I recommend writing code like that:
return x++, 0;
You can't do that for break
because it doesn't accept an expression.
The comma operator is for expressions.
The return
statement and other pure statements are not expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With