Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of commas in a conditional statement?

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?

like image 909
Abdul Rehman Avatar asked Nov 06 '15 07:11

Abdul Rehman


People also ask

What is the advantage of a comma operator?

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.

What is the purpose of the commas in arguments?

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.

What is the purpose of the comma operator give an example?

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.

What are the use of comma and conditional operator in C?

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.


1 Answers

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.

like image 123
Jon Jagger Avatar answered Sep 19 '22 03:09

Jon Jagger