The code below gives an answer (further below), that I do not understand.
#include <stdio.h>
int fA (int x) {
int w = x;
printf("%d", x);
if (x > 4)
w += fA(x - 2);
if (x > 2)
w += fA(x - 4);
printf("%d", x);
return w;
}
int fB (int x) {
if (x < 1)
return 1;
int w = x;
if (x > 2)
w = w * fB(x - 1);
if (x > 1)
w= w + fA(x - 1);
return w;
}
int main (void) {
printf("\n %d %d \n", fA(6), fB(3));
return 0;
}
it prints
112264004226
12 11
The question is why?
In my opinion it should starts with 6
.
Thanks!
Only the sequential-evaluation ( , ), logical-AND ( && ), logical-OR ( || ), conditional-expression ( ? : ), and function-call operators constitute sequence points, and therefore guarantee a particular order of evaluation for their operands.
There is no concept of left-to-right or right-to-left evaluation in C, which is not to be confused with left-to-right and right-to-left associativity of operators: the expression f1() + f2() + f3() is parsed as (f1() + f2()) + f3() due to left-to-right associativity of operator+, but the function call to f3 may be ...
Order of evaluation refers to the operator precedence and associativity rules according to which mathematical expressions are evaluated.
The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.
There is no guarantee that parameters to a function will be evaluated in any particular order.
So when you call printf
with fA(6)
and fB(3)
as parameters, the compiler is free to call either one before the other.
In this particular case, fB(3)
was evaluated first. But if you use a different compiler, it might evaluate fA(6)
first.
There's no defined order. This depends on compiler, for example on:
# gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include- dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin14.5.0
Thread model: posix
this produces
640042261122
12 11
Moreover - the same compiler may decide order to be different for optimization
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With