Pass By Value vs. Pass By Reference in C

 

C’s default behavior is to pass variables by value, meaning a copy of the original value is sent to the method being called. Any changes made to the variable inside the method being called will not affect the original variable, as shown below:

 

 
#include <stdio.h>
 
void AddOne(int iNumber);
 
int main()
{
 
        int a = 10;
 
        printf("main(): Prior to method, a = %d.", a);
        printf("\n");
 
        AddOne(a);
 
        printf("main(): After method, a = %d.", a);
        printf("\n");
 
        return 0;
}
 
void AddOne(int iNumber)
{
        iNumber = iNumber + 1;
}
 
 
Execution Output:
main(): Prior to method, a = 10.
main(): After method, a = 10.
 

 

 

However, if you would like to modify the original variable it is necessary to pass the value by reference, ie. passing the address of the original variable. This is accomplished by the following:

 

 
#include <stdio.h>
 
void AddOne(int *iNumber);
 
int main()
{
        int a = 10;
 
        printf("main(): Prior to method, a = %d.", a);
        printf("\n");
 
        AddOne(&a);
 
        printf("main(): After method, a = %d.", a);
        printf("\n");
 
        return 0;
}
 
void AddOne(int *iNumber)
{
        *iNumber = *iNumber + 1;
}
 
 
Execution Output:
main(): Prior to method, a = 10.
main(): After method, a = 11.
 

 





;