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

  • A+

I can write this 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 error 

same thing with for loop

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 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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: