c++ - Is undefined behavior in given code? -
what return value of f(p,p), if value of p initialized 5 before call? note first parameter passed reference, whereas second parameter passed value.
int f (int &x, int c) { c = c - 1; if (c==0) return 1; x = x + 1; return f(x,c) * x; }
options are:
- 3024
- 6561
- 55440
- 161051
i try explain:
in code, there 4 recursive calls parameters (6,4), (7,3), (8,2) , (9,1). last call returns 1. due pass reference, x in previous functions 9. hence, value returned f(p,p) 9 * 9 * 9 * 9 * 1 = 6561.
this question competitive exam gate, (see q.no.-42). answer key given gate "marks all" (means there no option correct.) key set-c, q.no.-42. somewhere explained as:
in gate 2013 marks given same code in c/c++ produces undefined behavior. because *
not sequence point in c/c++. correct code must replace
return f(x,c) * x;
with
res = f(x,c); return res * x;
but given code works fine. gate's key wrong? or mistake question?
return f(x,c) * x;
the result of operation depends on order in 2 things evaluated. since cannot predict order they'll evaluated, cannot predict result of operation.
Comments
Post a Comment