Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is order of expressions in if statement important

Suppose I have an IF condition :

if (A || B) 
    ∧
    |
    |
   left
{ 
   // do something  
}

Now suppose that A is more likely to receive a true value then B , why do I care which one is on the left ?

If I put both of them in the IF brackets , then I know (as the programmer of the code) that both parties are needed .

The thing is , that my professor wrote on his lecture notes that I should put the "more likely variable to receive a true" on the left .

Can someone please explain the benefit ? okay , I put it on the left ... what am I gaining ? run time ?

like image 461
JAN Avatar asked Aug 25 '12 04:08

JAN


People also ask

Does order matter in IF statements?

Yes, the order of the conditions matters. In your code, you test if(a==b) first. If all 3 integers are the same, then this will be true and only return c; will execute.

What is the importance of if statement?

An if statement lets your program know whether or not it should execute a block of code. Comparison-based branching is a core component of programming. The concept of an if-else or switch block exists in almost every programming language.

What must the condition in an if statement evaluation?

The syntax for if statement is as follows: if (condition) instruction; The condition evaluates to either true or false. True is always a non-zero value, and false is a value that contains zero.

How is if statement different from if-else statement?

Conditional Statements Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.


2 Answers

Its not just about choosing the most likely condition on the left. You can also have a safe guard on the left meaning you can only have one order. Consider

if (s == null || s.length() == 0) // if the String is null or empty.

You can't swap the order here as the first condition protects the second from throwing an NPE.

Similarly you can have

if (s != null && s.length() > 0) // if the String is not empty

The reason for choosing the most likely to be true for || or false for && is a micro-optimisation, to avoid the cost of evaluated in the second expression. Whether this translates to a measurable performance difference is debatable.

like image 168
Peter Lawrey Avatar answered Sep 23 '22 05:09

Peter Lawrey


I put it on the left ... what am I gaining ? run time ?

Because || operator in C++ uses short-circuit evaluation.
i.e: B is evaulated only if A is evaluated to a false.

However, note that in C++ short-circuit evaluation is guaranteed for "built in" data types and not custom data types.

like image 34
Alok Save Avatar answered Sep 22 '22 05:09

Alok Save