I have the following piece of code :
int f(int &x, int c){
c = c - 1;
if (c == 0) return 1;
x = x + 1;
return f(x, c)*x;
}
int p = 5;
std::cout << f(p, p) << std::endl;
9^4
x
x
return
return x*f(x, c);
3024 (6*7*8*9)
Operator*
When you write:
f(x,c)*x
the compiler may choose to retrieve the stored value in x
(for the second operand) either before or after calling f
. So there are many possible ways that execution could proceed. The compiler does not have to use any consistency in this choice.
To avoid the problem you could write:
auto x_temp = x;
return f(x, c) * x_temp;
Note: It is unspecified behaviour; not undefined behaviour because there is a sequence point before and after any function call (or in C++11 terminology, statements within a function are indeterminately-sequenced with respect to the calling code, not unsequenced).