Is there any guarantee that the ifs of the if-else if-else if-else
block are checked in the order in which they were written.
I ask about this because I often try to optimize my code by setting the most common cases, and I want to know if some optimizations made by the compiler can change the order in which if is tested.
So, if I write this code:
if (cond1) // First if (for the case I have the most often) { doSomething1(); } else if (cond2) // Second if (for the second case I have the most often) { doSomething2(); } else if (cond3) // Third if (for the third case I have the most often) { doSomething3(); } else { doElse(); }
Is there any guarantee that after compilation (for release) the first will be checked, then the second if, then the third if (and finally else is satisfied if none of the conditions were true).
I know that when debugging, ifs are executed in the order I wrote them, but whether it will be true when the program is compiled for release (I mainly use the latest version of g ++ and visual studio).
In addition, since the condition may affect the environment (for example, if (i=a)
or if(myfunction())
), they should be executed as written, but I wonder if there is any optimization that the compiler could do , change the order in which if is tested. Especially if the condition does not have such side effects:
void test(int a) { if (a == 1) { doSomething1(); } else if (a == 2) { doSomething1(); } else if (a == 3) { doSomething1(); } else { doSomething1(); } }
Mesop source share