I thought I understand how sequence points work in C++, but this GeeksQuiz question puzzled me:
int f(int &x, int c) {
c = c - 1;
if (c == 0) return 1;
x = x + 1;
return f(x, c) * x;
}
int main() {
int p = 5;
cout << f(p, p) << endl;
return 0;
}
The “correct” answer to this question says it prints 6561. Indeed, in VS2013 it does. But isn't it UB anyway because there is no guarantee which will be evaluated first: f(x, c)
or x
. We get 6561 if f(x, c)
is evaluated first: the whole thing turns into five recursive calls: the first four (c = 5, 4, 3, 2
) continue on, the last one (c = 1) terminates and returns 1, which amounts to 9 ** 4
in the end.
However, if x
was evaluated first, then we'd get 6 * 7 * 8 * 9 * 1
instead. The funny thing is, in VS2013 even replacing f(x, c) * x
with x * f(x, c)
doesn't change the result. Not that it means anything.
According to the standard, is this UB or not? If not, why?
3024
forx * f(x, c)
(and6561
forf(x, c) * x
). – Unfix