Call by value and Call by reference in C Programming

Call by value and Call by reference in C are two ways to pass arguments in a function

Lets see above one by one

Call by value

Whenever we call a function and passes the value of variable to the called function is called call by value.

#include 
void swap(int x, int y);		/* function declaration */

 int main ()
 {
   int a = 10;
   int b = 20;
 
   printf("Value of 'a' before swap=  %d\n", a );
   printf("Value of 'b' before swap=  %d\n", b );
    
   swap(a, b);		// calling a function  swap & passes the value of variable
 
   printf("Value of 'a' after  swap=  %d\n", a );
   printf("Value of 'b' after  swap=  %d\n", b );
 
   return 0;
}

void swap(int x, int y) 		// function definition to swap the values 
{
   int temp;

   temp = x;
   x = y;   
   y = temp; 
  
   return;
}

OUTPUT

Value of 'a' before swap=  10
Value of 'b' before swap=  20
Value of 'a' after  swap=  10
Value of 'b' after  swap=  20

Call by reference

Whenever we call a function and passes the reference of variable to the called function is called call by reference.

In the call by reference, to pass the reference of the variable we use pointer.

#include 

void swap(int * x, int * y); /* function declaration */
int main() {
    int a = 10;
    int b = 20;

    printf("Value of 'a'  before swap= %d\n", a);
    printf("Value of 'b'  before swap= %d\n", b);

    swap( & a, & b); //call function swap and passes the reference of variable 

    printf("Value of 'a'  after  swap= %d\n", a);
    printf("Value of 'b'  after  swap= %d\n", b);

    return 0;
}

void swap(int * x, int * y) // function definition to swap the values 
{
    int temp;

    temp = * x;
    * x = * y;
    * y = temp;
    return;
}

OUTPUT

Value of 'a' before swap=  10
Value of 'b' before swap=  20
Value of 'a' after  swap=  20
Value of 'b' after  swap=  10