Search code examples
c++comma-operator

Can compiler skip evaluation of comma operator's left operand?


Compiler optimization can sometimes skip evaluation of certain statements which have no consequence. However, does this apply to the comma operator too?

The following code runs without any error on ideone, but I expected it to crash.

#include <iostream>

int main() {
    int x = (1/0, 2);
    std::cout << x << std::endl;
}

The program does crash if I change the statement to int x = 1/0;


Solution

  • Compiler optimizations use the As-if rule.

    The as-if rule

    Allows any and all code transformations that do not change the observable behavior of the program

    So Yes, the compiler can optimize this. Check the following modified sample:

    #include <iostream>
    
    int main() 
    {
        int y = 1;
        int x = (y=1/0, 2);
        std::cout << x << std::endl;
        //std::cout << y << std::endl;
    } 
    

    Commenting the last line compiles and executes this code correctly while uncommenting it gives you the expected undefined behavior.

    As @jogojapan correctly points out,
    It is important to note that compiler optimizations are not guaranteed by the standard and divide by zero is a Undefined behavior. So this code does have an undefined behavior. Whether the observable behavior is because of compiler optimizing out the divide by zero or due to undefined behavior we can never know. Technically, it is Undefined behavior all the same.