C++ – IF statement with OR logical operator

cif statementoperators

Just a basic question on IF statements in programming languages, specifically C++. Consider the following basic code example:

int i = 2;

if(i == 2 || i == 4) {
    //do something
}

Because the first condition would equate to true, are CPU cycles wasted on the second condition? Sorry for the Programming 101 question, just would like to know.

Best Answer

Possible compiler optimization aside, C and C++ language specs explicitly says that expression such as if(i == 2 || i == 4) will be evaluated left to right and second part after || will not be evaluated if first part is true. This is particularly important when right part after || is an expression that has side effects. For example, if it is a function call that function will not be called. This rule is often exploited by some (rather tricky) C/C++ code pieces.

Related Topic