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 ?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With