0

What is the return value of f(p, p), if the value of p is initialised to 5 before the call? Note that the first parameter is passed by reference, whereas the second parameter is passed by value.

int f(int& x, int c)
{
  c = c — 1;
  if (c = = 0)
    return 1;

  x = x + 1;
  return f(x, c) * x;
}
Mat
  • 202,337
  • 40
  • 393
  • 406
  • This will help you https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value/430958 – Pritesh Jul 26 '20 at 06:09
  • Have you tried it? – n. m. could be an AI Jul 26 '20 at 06:17
  • The code is invalid. – CiaPan Jul 26 '20 at 07:07
  • @CiaPan - why do you say the code is invalid? It is fine, the only limitation is you cannot pass a integer literal as `x` (and you have to remove the Unicode characters and replace them with ASCII) – David C. Rankin Jul 26 '20 at 08:11
  • I say it is invalid because two consecutive `=` operators in `if (c = = 0)` do not fit C++ grammar. – CiaPan Jul 26 '20 at 09:02
  • Yes, you are correct there, but since the em-dash `'-'` was a Unicode character -- that looked more like a copy/paste from web error than intentional. – David C. Rankin Jul 26 '20 at 09:16
  • @DavidC.Rankin I know. And may be my comment was too short, and unkind due to that. But, whatever the origin of the code was, when fed to a compiler the code will appear invalid. Anyway, the question looks like a test problem to me. The _'Note that...'_ part sounds like it was said by a teacher, someone who knows precisely what the trick is in the code and what the answer should be. – CiaPan Jul 26 '20 at 09:49

1 Answers1

2

I suspect UB here, as you have no guarantee whether the x value will be fetched for multiplication before or after execution of the recursive call to f.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
CiaPan
  • 9,381
  • 2
  • 21
  • 35