YiFei YiFei - 1 year ago 63
C Question

Arrangement of 2 by 2 condition in if statement in C-family language

When programming, I'm usually dealing with two sets of conditions combined together, like:

if (A && B){...}
else if (!A && B){...}
else if (A && !B){...}
else if (!A && !B){...}

It can also be resolved using nested if statements.

if (A){
if (B) {...}
else {...}
else {
if (B) {...}
else {...}

EDIT: Some new thoughts, what about I firstly evaluate both A and B and store as temporary variable (then do as the first approach) in case that the evaluation of A and B both have no side-effect?

So my question is there any performance difference between them and what about their readability?

I code in C++, if matters.

Answer Source

The two cases are not the same. In the second case, A and B will each be evaluated exactly once. In the first case, A and B will evaluated a number of times, depending upon their value.

While this almost certainly won't affect the optimization of the typical case, it will matter if A or B have side effects.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download