Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Understanding procedure in C++

I have the following code in C++:

#include <iostream>
using namespace std;

int x;

void p(int a, int &b) {
    cout << x << " " << a << " " << b << endl;
    if (a < b) {
        a = x+b;
    }
    else {
        --x;
        b += a;
        a = x/2;
        cout << x << " " << a << " " << b << endl;
        p(b-x, a);
    }
    cout << x << " " << a << " " << b << endl;
}

int main() {
    x = 17;
    p(42, x);
    cout << x << endl;
}

The output of this code is the following, which I don’t understand:

17 42 17
58 29 58
58 0 29
58 87 29
58 29 58
58

Specifically, in main, x=17 assigns a global parameter. It starts calculating p(a=42,&b=17). It prints out: x = 17 (global),a = 42 ,b = 17 (pointer). Good so far!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Next, it goes to if. if 42<17 is not satisfied and goes to else, in which x is decremented by one so x=17-1=16. Not 58.

What is going on? Can someone please explain?

>Solution :

Your parameter b is a reference (ie, alias) to an int variable. In this case, it refers to the global variable x, since that is what main() is passing in. So, x and b are separate names for the same memory block that is holding an int value. As such, anything you do to x is reflected in b and vice versa.

When your code goes to the else for the 1st time, the value of x (and thus b) is 17. You decrement x (and thus b) by 1, and then increment b (and thus x) by a (42). So, you are actually incrementing x by 41, hence why x becomes 58 (17-1+42=58).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading