About local variables and global variables in C and C++

First look at an example

#include <iostream>
using namespace std;

int change(int r)
{
    r++;
}

int main()
{
    int x = 5;
    change(x);
    cout << "x = " << x << endl;
    return 0;
}

 After passing x to the change function, and then outputting the value of x, it will not change, because the x passed into the change function is only equivalent to a copy of the original x in the main function, and the final output is still 5;

 

If you want to really change the value of x, you should use a reference in C++, that is, add an ampersand before the formal parameter passed in the change function:

#include <iostream>
using namespace std;

int change(int &r)
{
    r++;
}

int main()
{
    int x = 5;
    change(x);
    cout << "x = " << x << endl;
    return 0;
}

 

   

Of course, if you use plain C (plain c) syntax to achieve, you need to use pointers, you can get the same effect

#include <iostream>
using namespace std;
    
void change(int *r)
{
    ++(*r);
}

int main()
{
    int x = 5;
    int *p = &x;
    printf("%d\n",x);
    change(p);
    printf("%d\n",x);
    return 0;
}

 

So, if you want to define a reference variable, how should it be implemented?

code show as below:

#include <iostream>
using namespace std;

int a = 5,b = 6;
int *p = &a;
int *q = &b;
    
void change(int *&r)
{
    r = q;
}

int main()
{
    cout << *p << endl;
    change(p);
    cout << *p << endl;
    return 0;
}

 

 

 

Guess you like

Origin blog.csdn.net/smallrain6/article/details/107387773