C Programming

Passing Arguments

Posted on 20th October 2014

When a C program calls a function, the arguments of that function are copied from the calling function to the function definition by default. This method of passing arguments from calling function to the function definition is called Pass-by-Value. Any change that you make to the arguments inside the function will not change the argument's value in the calling function. This is demonstrated in the example below

Example

#include <stdio.h>
void count_update(int, int);

void count_update(int i, int j) 
{
	i = i + 1;
	j = j + 2;
	printf("The value of i inside count_update function is %d \n", i);
	printf("The value of j inside count_update function is %d \n", j);

	return;
}

main() 
{
 int i, j;
 
 i = 10;
 j = 15;

 count_update(i, j);

 printf("The value of i inside main function is %d  \n", i);
 printf("The value of j inside main function is %d \n", j);
 
return 0;
}

The output of this program is

The value of i inside count_update function is 11
The value of j inside count_update function is 17
The value of i inside main function is 10
The value of j inside main function is 15

In the above example the value of variables i and j are modified by the count_update() function but their original values inside the main() function remains unchanged.

Another method of passing arguments to a function in C is called Pass by Reference. In this method you pass pointers as arguments to a function. Any modifications the function makes on the pointer's value will also be reflected on the calling function. Pass by Reference is explained in detail in the Pointers in Functions chapter of this tutorial.

Post a comment

Comments

Nothing yet..be the first to share wisdom.