I am curious about the exact definition of the C standard about variable assignment within a conditional clause. Here is a small example:
int foo() {
...
}
int bar() {
...
}
int main () {
int a, b, x, y;
...
if ( (a = foo()) == x && (b = bar() == y ) {
...
}
...
}
A test with GCC revealed that if (a = foo()) != x
, b = bar()
will not be executed. On the one hand this behavior is optimal, as it will not waste any time with the calculation of bar()
. On the other hand, though, the value of b
is somewhat undefined, because it depends on the result of foo()
, which actually has nothing to do with b
.
I wonder if there is an explicit definition for such cases in the C standard and what the reasons for that definition would be. And finally, what is considered to be best practice for writing such code?