简体   繁体   中英

Why does return 0 or break not work with the comma operator?

I can write the code if(1) x++, y++; instead of if(1) {x++; y++;} 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

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.

The comma operator is a binary operator that takes two values. In this way it is the same as + or * . Whereas + adds two values and returns the result, and * multiplies two values and returns the result, the comma operator simply ignores the value to the left and returns the value on the right.

2 + 5 has value 7

2 * 5 has value 10

2 , 5 has value 5 , simply the operand to the right of the operator.

And so you can't write 2,break for the same reason that you can't write 2+break . Because break is a statement, not a value.

What use is a binary operator that ignores one of its operands? The comma operator ignores the value of the left operand, but the expression is still evaluated. Any side-effects of that expression are still realized. Consider:

i = 2;
j = 5;
i++, j++;

First the two expressions are evaluated. i++ returns the value 2 , and then increments i . j++ returns the value 5 , and then increments j . Finally the comma operator is applied to these two values: 2,5 which ignores the 2 and returns the 5 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM