Pass by Reference

To allow a function to act upon data that is being passed to it directly, the ampersand & 'address of' operator is used on the variable as the argument within the function call.

 

function( &myVar ) ;

 

The function's interface then accepts the address of the passed in argument as a pointer:

 

function( *pointer );

 

which allows direct access to the variable being passed in.

Compile & run:

1st value of myVar in main: 42
1st value of myVar in function: 42
2nd value of myVar in function: 17
2nd value of myVar in main: 17

Leave a Reply