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:

  1. 3024
  2. 6561
  3. 55440
  4. 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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -