Assume we have code like this in C or C++:
foo(bar());
What is the function execution order in this case?
- Is it required that
bar()
is called first, andfoo()
is called no earlier thanbar()
returns, in which casefoo()
is passed the return value ofbar()
? - Is it permitted that the compiler reorders the above, namely that it calls
foo()
first, and delays callingbar()
until in the code offoo()
the value offoo()
’s parameter is actually needed?
Case 2 could be useful for optimization should foo()
be defined like this:
void foo(someType par) {
if(someTest())
baz1();
else
baz2(par);
}
In which case calling bar()
could even be completely skipped if someTest()
returns false
.
However, case 2 would also make the programmer have to be more careful, as it could sometimes lead to subtle bugs (for example with recurrence).