What is the advantage of commas in a conditional statement?

后端 未结 7 1724
醉酒成梦
醉酒成梦 2021-02-03 17:25

We can write an if statement as

if (a == 5, b == 6, ... , thisMustBeTrue)

and only the last condition should be satisfiable to ent

7条回答
  •  遥遥无期
    2021-02-03 17:36

    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.

提交回复
热议问题