What will be printed out as a result of the following program's execution?

#include <stdio.h>

void ampersand( int n, int &k );

int main()
{    
    int n=5;
    int k=10;
    
    ampersand( n, k );
    printf( "n=%d &k=%d\n", n, k );

    return 0;
}

void ampersand( int n, int &k )
{
    k -= 5;
    --n;
}
Explanation
By definition, pass by value means you are making a copy in memory of the actual parameter's value that is passed in, a copy of the contents of the actual parameter. Use pass by value when when you are only "using" the parameter for some computation, not changing it for the client program. In the example above n is passed by value and therefore is not changed.

In pass by reference (also called pass by address), a copy of the address of the actual parameter is stored. Use pass by reference when you are changing the parameter passed in by the client program. The k variable is passed by reference and therefore is changed.
Source: Function pass by value vs. pass by reference

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback