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.

 

#include <stdio.h>

void function(int *myVar); //declare the function prototype

int main() {

	int myVar = 42; //define a local variable

	printf("1st value of myVar in main: %dn", myVar); //print value of myVar

	function( &myVar ); //call and pass myVar to globalFunction

	printf("2nd value of myVar in main: %dn", myVar); //print value of myVar

	return 0;
}

void function(int *myVar) { //void function since nothing being returnef

	printf("1st value of myVar in function: %dn", *myVar); //print value of myVar

	*myVar = 17; //variable is now being assigned a new value

	printf("2nd value of myVar in function: %dn", *myVar); //print value of myVar
}

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