Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++;}, 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 
like image 559
Nayem Avatar asked Aug 21 '18 06:08

Nayem


People also ask

How does a comma operator 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.

How does comma operator work in C?

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.

Which operator works on list of comma separated values?

It is comma operator.

How is comma operator useful in a for loop in C?

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.


2 Answers

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.

like image 177
Rakete1111 Avatar answered Oct 03 '22 22:10

Rakete1111


The comma operator is for expressions.

The return statement and other pure statements are not expressions.

like image 41
Yunnosch Avatar answered Oct 03 '22 21:10

Yunnosch