简体   繁体   中英

C++ program for address and variables

The output for this code is:

9

And I'm not sure what it changes in the function add1 . And also what does this &n mean and what does it do when we assign the i to &n ?

#include <iostream>

using namespace std;

int add1(int &n){
    n++;
    return n;
}

int main(){
    int m = 0;

    for (int i = 0; i < 5; i++){
        m += add1(i);
    }
    cout << m ;
    cout << "\n\n";

    return 0;
}

When & is used in a parameter list, it will cause that parameter to be passed as a reference to the function.

What this means is that n in your function add1 , will point to the same space in memory as i in your main function. Changes to n will also be reflected in i , as they will simply act as different names for the same thing.

Variable i is passed into add1 as a reference parameter, so every round i is increased by two:

1st round: i = 0, m = 1
2nd round: i = 2, m = 4
3rd round: i = 4, m = 9

If you have a function like this

int add1( int n )
          ^^^^^
{
   n++;

   return n;
}

and call it like

m += add1(i);

Then the function deals with a copy of the value of vatiable i .

You can imagine it the following way if to build it in the body of the loop

for ( int i = 0; i < 5; i++ )
{
    // m += add1(i);
    // function add1
    int n = i;
    n++;
    m += n;
}

When a function is declared like this

int add1( int &n )
          ^^^^^
{
   n++;

   return n;
}

Then it means that the parameter is a reference to the corresponding original argument. You can consider it just as an alias for the argument.

In this case you can imagine it the following way if to build it in in the body of the loop

for ( int i = 0; i < 5; i++ )
{
    // m += add1(i);
    // function add1
    i++; 
    m += i;
}

So the variable i is changed twice in the function add1 because it is directly used in the function by means of the reference n and in the control statement of the loop.

Here we are passing a parameter to the add1() function by using pass by reference. To pass a variable by reference, we simply declare the function parameters as references rather than as normal variables.

In above code,

int add1(int &n){ // n is a reference variable
    n++;
    return n;
}

When the function is called, n will become a reference to the argument. Since a reference to a variable is treated exactly the same as the variable itself, any changes made to the reference are passed through to the argument!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM