Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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.

like image 747
Ayush Pandey Avatar asked Oct 03 '18 06:10

Ayush Pandey


1 Answers

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

[expr.mul]/4

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

like image 63
llllllllll Avatar answered Oct 26 '22 17:10

llllllllll