Pass by Value

If the argument within the parentheses of a function call is a variable, constant (or some other expression) it means that it is first evaluated and a COPY is then passed to the function as its input.

 

The function uses the copy of the passed in argument, and executes any statements upon that copy locally within the function.

 

Once the execution within the function is complete, control returns to the point of which the call was made, and any locally changed data within the called function is lost.

 

#include <stdio.h>

void function(int myInt); //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 returned

	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: 42

 

Leave a Reply