Search code examples
c++c++11c++14integer-divisiondivide-by-zero

"if" statement in c++ doesn't evaluate conditions from left to right


I was referring to the question ""IF" argument evaluation order?" for understanding the evaluation order for "if" statement in c++.

Here is the code where the conditions in if statements are evaluated in a wrong order.

#include <iostream>

using namespace std;

int main()
{
    int t = 0;
    if((1 / t) == 1 && t != 0)
    {
        cout << "0" << endl;
    }

    cout << "1" << endl;

    return 0;
}

The result is 1 instead of floating point exception.


Solution

  • Division-by-zero is undefined behavior. Anything can happen.

    [expr.mul]/4

    If the second operand of / or % is zero the behavior is undefined.