Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

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.

like image 980
YiFei Avatar asked Mar 11 '23 13:03

YiFei


1 Answers

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.

like image 160
Robᵩ Avatar answered Apr 06 '23 07:04

Robᵩ