What is the advantage of commas in a conditional statement?

后端 未结 7 1729
醉酒成梦
醉酒成梦 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

    In short: Although it is legal to do so, it usually doesn't make sense to use the comma operator in the condition part of an if or while statement (EDIT: Although the latter might sometimes be helpful as user5534870 explains in his answer).

    A more elaborate explanation: Aside from its syntactic function (e.g. separating elements in initializer lists, variable declarations or function calls/declarations), in C and C++, the , can also be a normal operator just like e.g. +, and so it can be used everywhere, where an expression is allowed (in C++ you can even overload it).
    The difference to most other operators is that - although both sides get evaluated - it doesn't combine the outputs of the left and right expressions in any way, but just returns the right one.
    It was introduced, because someone (probably Dennis Ritchie) decided for some reason that C required a syntax to write two (or more) unrelated expressions at a position, where you ordinarily only could write a single expression.

    Now, the condition of an if statement is (among others) such a place and consequently, you can also use the , operator there - whether it makes sense to do so or not is an entirely different question! In particular - and different from e.g. function calls or variable declarations - the comma has no special meaning there, so it does, what it always does: It evaluates the expressions to the left and right, but only returns the result of the right one, which is then used by the if statement.

    The only two points I can think of right now, where using the (non-overloaded) ,-operator makes sense are:

    1. If you want to increment multiple iterators in the head of a for loop:

      for ( ... ; ... ; ++i1, ++i2){
          *i2=*i1;
      }
      
    2. If you want to evaluate more than one expression in a C++11 constexpr function.

    To repeat this once more: Using the comma operator in an if or while statement - in the way you showed it in your example - isn't something sensible to do. It is just another example where the language syntaxes of C and C++ allow you to write code, that doesn't behave the way that one - on first glance - would expect it to. There are many more....

提交回复
热议问题