Does the compiler always check all the conditions in an if statement?

if (a && b) { /* Do something */ }

Does the compiler always compile the code above to check for "a" first and then "b"? If "a" is already false does the compiler continue checking "b"? Is it different between compiler versions or debug vs optimize mode? Sometimes "b" is a function that needs to run any frames so I don't want it to be optimized out if "a" is false. Other times, "b" isn't important and may be very expensive so I want it to be ignored if "a" is already false.

What about "else if"? If the first "if" statement is already true does the compiler continue to check the "else if" condition?

Evaluating only a and not doing b is called "short circuit evaluation" - and C specification says that it must happen. So compiler generates code that does this regardless of optimizations.

Same thing happens with a || b expression. See https://en.cppreference.com/w/c/language/operator_logical for more information.

Similar thing happens with if/else-if chains. Once the condition evaluates true, then the body of that particular condition is executed and no more else-if conditions will be checked.

So if I have an important function that runs every frame then doing something like this won't work: if (a && Important()), right? I need to run the function first and cache the value of it.

Yes, that is right.


Replying to longtran2904 (#25053)