Use of reference variables in C++

Viewed 87

I came across the following question:

#include <stdio.h>

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;
    printf("%d", f(p, p));
}

As far as I have worked out, the recursion calls should work, and with each recursion call, value of c should reduce by 1 and value of x should increase by 1 . However, if I calculate it that way, the answer comes out to be 3024. However, on executing, the output comes out to be 6561. I am not really sure how this answer is coming.

I have the link to the article from where this question is taken, but I fail to understand how x will remain constant as is described in this link: https://www.geeksforgeeks.org/c-references-question-1/

Can someone help me with the working behind this code?

1 Answers

There can be any result, due to Undefined behavior.

Since the x is passed by reference, the last assign will matter. Thus, we have:

9*9*9*9*1=6561

We delay the evaluation of the f(x, c) * x, where all the subsequent recursive calls will have access to the x. We increment the x this way until the c is equal to 0, means we increment the x up to it being 9.

When we hit the base case (the c == 0), the current call returns 1, while the x is already 9.

Then we evaluate the multiplication 1 * x * x * x * x, where x is equal to 9. Thus, the 6561.

Flawless explanation? Not so much.

The fun part is that there is no concept of left-to-right or right-to-left evaluation in C++:

Order of evaluation of any part of any expression, including order of evaluation of function arguments is unspecified (with some exceptions listed below). The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.

Means, that though this logic gets a pass this time, it may won't be this way next time for me or if you run it yourself.

Related