mrks mrks - 1 year ago 79
C Question

if with multiple conditions, order of execution

In an if statement with multiple conditions is second executed if the outcome is clear after checking the first condition?


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

If I swap the conditions a seg fault may occur for negative values of i but this way the memory debugger doesn't find a problem. Can I be sure that this works always or do have have to use nested if statements?

Uri Uri
Answer Source

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 it is not 4, it will not be incremented at all.