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

  • A+
Category:Languages

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.

 


Division by zero is undefined.

Thus, a compiler may assume that t is not zero.
It can also deduce that 1/t is not 1 since t isn't 1.

Having done that, it can remove the entire conditional.

For instance, g++ 8.2 does that unless you disable optimisations; it generates the equivalent of

int main() {     cout << "1" << endl;     return 0; } 

Today's lesson is "don't rely on undefined behaviour to be any particular behaviour".

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: