Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of execution for an if with multiple conditionals

Tags:

c

In an if statement with multiple conditionals, is the second conditional executed if the outcome of the first is clear?

example:

if(i>0 && array[i]==0){ } 

If I swap the conditionals a segfault may occur for negative values of i, but this way no segfault occurs. Can I be sure that this always works or do have have to use nested if statements?

like image 223
mrks Avatar asked Mar 16 '10 16:03

mrks


People also ask

How do you write an if statement with multiple conditions?

When you combine each one of them with an IF statement, they read like this: AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False) OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False) NOT – =IF(NOT(Something is True), Value if True, Value if False)

Can IF statement have 2 conditions in C?

nested-if in C/C++ Nested if statements mean an if statement inside another if statement. Yes, both C and C++ allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement.

Which of the following is used to execute one statement from multiple conditions?

The if-else-if statement is used to execute one code from multiple conditions. It is also called a multipath decision statement.

Can you have 3 conditions in an if statement JavaScript?

Using either “&&” or “||” i.e. logical AND or logical OR operator or combination of can achieve 3 conditions in if statement JavaScript.


1 Answers

This type of evaluation is called short-circuiting. Once the result is 100% clear, it does not continue evaluating.

This is actually a common programming technique. For example, in C++ you will often see something like:

if (pX!=null && pX->predicate()) { bla bla bla } 

If you changed the order of the conditions, you could be invoking a method on a null pointer and crashing. A similar example in C would use the field of a struct when you have a pointer to that struct.

You could do something similar with or:

if(px==null || pX->isEmpty()} { bla bla bla } 

This is also one of the reasons that it is generally a good idea to avoid side effects in an if condition.

For example suppose you have:

if(x==4 && (++y>7) && z==9) 

If x is 4, then y will be incremented regardless of the value of z or y, but if x is not 4, it will not be incremented at all.

like image 139
Uri Avatar answered Sep 20 '22 09:09

Uri