Search code examples
c++debuggingwarningscomma-operator

Should a diagnostic be emmited for discarded value expressions that do not have side effects?


After quite some debugging time I felt silly to discover a goof in my code that boils down to something like this :

int main()
{
    double p1[] = { 1, 2, 3 };
    double p2[] = { 1, 2, 3 };
    int color = 1;
    bool some_condition = true;

    if (some_condition) (p1, p2, color);
}

The (p1, p2, color) expression evaluates to its last operant, but should the compiler protect me in some way ? (Visual Studio told nothing)

And yes you guessed it right, I wanted to call a draw function : Draw(p1, p2, color)


Solution

  • In C++ the expression (p1, p2, color) forces the compiler to interpret the commas inside the parentheses as the sequential-evaluation operator. The sequential-evaluation operator is a binary operator that evaluates its first operand as void and discards the result, it then evaluates the second operand and returns its value and type. Therefore, the expression (p1, p2, color) is going to be evaluated in the following way:

    1. First p1 is evaluated and discarded, then (p2, color) is evaluated and the result (p2, color) is returned.
    2. First p2 is evaluated and discarded, then color is evaluated and the result color is returned.

    Thus the statement:

    if (some_condition) (p1, p2, color);
    

    Is equivalent to:

    if (some_condition) color;
    

    Some compilers might raise a warning because during the evaluation of the expression (p1, p2, color) the evaluations of p1 and p2 will result in unused:

    CLANG LIVE DEMO GCC LIVE DEMO (As you already mentioned Visual Studio will raise no warning at all.)

    Apart from these warnings the code is legitimate C++ (i.e., C++ syntax isn't violated).

    Now, whether the compiler should protect you is debatable. In my humble opinion it should protect you, since such expressions although correct from C++ syntax point of view might result, in very hard to spot bugs (e.g., the case of assingment inside an if expression).