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?
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 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:
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
xis4, thenywill be incremented regardless of the value ofzory, but ifxis not4, it will not be incremented at all.