Search code examples
c++if-statementcomma-operator

Using the comma operator in if statements


I tried the following:

if(int i=6+4==10)
    cout << "works!" << i;

if(int i=6+4,i==10)
    cout << "doesn't even compile" << i;

The first works fine while the second doesn't compile. Why is this?

EDIT: Now I know that the first one may not work as I intend it to. The value of i inside the if scope will be 1, not 10. (as pointed out by one of the comments on this question).

So is there a way to initialize and use a variable inside of an if statement at the same time similar to for(int i=0;i<10;i++)? So that you could produce something like if((int i=6+4)==10) (which will not compile) where the value of I inside the if scope would be 10? I know you could declare and initialize I before the if statement but is there a way to do this within the statement itself?

To give you an idea why I think this would be usefull.

 if(int v1=someObject1.getValue(), int v2=someObject2.getValue(), v1!=v2)
    {
        //v1 and v2 are visible in this scope 
        //and can be used for further calculation without the need to call
        //someObject1.getValue() und someObject2.getValue() again.
    }
    //if v1==v2 there is nothing to be done which is why v1 und v2
    //only need to be visible in the scope of the if.

Solution

  • The expression used as an initializer expression must be an assignment-expression so if you want to use a comma operator you must parenthesize the initializer.

    E.g. (not that what you are attempting makes much sense as 6 + 4 has no side effects and the value is discarded and i == 10 uses the uninitialized value of i in its own initializer.)

    if (int i = (6 + 4, i == 10)) // behaviour is undefined
    

    Did you really mean something like this?

    int i = 6 + 4;
    if (i == 10)
    

    When using the form of if that declares a new variable the condition checked is always the value of the initialized variable converted to bool. If you want the condition to be an expression involving the new variable you must declare the variable before the if statement and use the expression that you want to test as the condition.

    E.g.

    int i;
    if ((i = 6 + 4) == 10)