OK, I'm a little embarassed to ask this question, but I just want to be sure...
It is known that C uses short circuit evaluation in boolean expressions:
int c = 0;
if (c && func(c)) { /* whatever... */ }
In that example func(c)
is not called because c
evaluates to 0
. But how about more sophisticated example where side effects of comparison would change the variable being compared next? Like this:
int c; /* this is not even initialized... */
if (canInitWithSomeValue(&c) && c == SOMETHING) { /*...*/ }
Function canInitWithSomeValue
returns true and changes value at given pointer in case of success. Is it guaranteed that subsequent comparisons (c == SOMETHING
in this example) uses value set by canInitWithSomeValue(&c)
?
No matter how heavy optimizations the compiler uses?
if
statement, because it can never run. Short circuit-evaluation would mean that if you hadif(func1() && func2()) { ... }
, and func1() evaluated to false at runtime (i.e. not definetely when compiling), then the code should not checkfunc2()
- the compiler should have crafted the machine code such that iffunc1()
is false,func2()
isn't called. – Jiggerypokeryint c = 0
was there to indicate thatc
is equal to0
at the time of comparision, I realize that in a case that simple the compiler would optimise the entireif
. – Mozart