We can write an if
statement as
if (a == 5, b == 6, ... , thisMustBeTrue)
and only the last condition should be satisfiable to enter the if
body.
why is it allowed?
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.
You use the comma operator, to separate two (ostensibly related) expressions. Later in the description: If you want to use the comma operator in a function argument, you need to put parentheses around it. That's because commas in a function argument list have a different meaning: they separate arguments.
Sometimes we assign multiple values to a variable using comma, in that case comma is known as operator. Example: a = 10,20,30; b = (10,20,30); In the first statement, value of a will be 10, because assignment operator (=) has more priority more than comma (,), thus 10 will be assigned to the variable a.
The comma operator (,) allows you to evaluate multiple expressions wherever a single expression is allowed. The comma operator evaluates the left operand, then the right operand, and then returns the result of the right operand.
Changing your example slightly, suppose it was this
if ( a = f(5), b = f(6), ... , thisMustBeTrue(a, b) )
(note the =
instead of ==
). In this case the commas guarantee a left to right order of evaluation. In constrast, with this
if ( thisMustBeTrue(f(5), f(6)) )
you don't know if f(5)
is called before or after f(6)
.
More formally, commas allow you to write a sequence of expressions (a,b,c)
in the same way you can use ;
to write a sequence of statements a; b; c;
. And just as a ;
creates a sequence point (end of full expression) so too does a comma. Only sequence points govern the order of evaluation, see this post.
But of course, in this case, you'd actually write this
a = f(5); b = f(6); if ( thisMustBeTrue(a, b) )
So when is a comma separated sequence of expressions preferrable to a ;
separated sequence of statements? Almost never I would say. Perhaps in a macro when you want the right-hand side replacement to be a single expression.
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