Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c
communitycreator

Call by value vs. call by reference in C

Divyanjali Vallapu Reddy

A function is a self-contained block of statements that perform a particular task.

Syntax

Call by value vs. call by reference

The parameters of functions can be passed in two ways:

  1. Call by value: A copy of the variable is passed to the function.

  2. Call by reference: An address of the variable is passed to the function.

Call by reference is preferred when we have to return more than one variable, like in C programming where we can only return one variable at a time. Call by reference can be achieved via pointers.

Code

Call by value

In the example below, we are simply swapping two numbers. Although the swapping took place inside the function, as you can see from the output, the output says the opposite. This happens because we have sent a copy of the variable instead of its exact address.

#include<stdio.h>
void swap(int n1, int n2)
{
  int temp = n1;
  n1 = n2;
  n2 = temp;

}
int main() {
    int x = 20;
    int y = 68;
    printf("The numbers before swapping n1 and n2 %d %d \n",x, y);
    swap(x, y);
    printf("The numbers after swapping n1 and n2 %d %d \n",x, y);
    return 0; 
}

Call by reference

In this example, the output shows the correct result. This happens because we have sent the exact address of the variable.

#include<stdio.h>
void swap(int *n1 ,int *n2)
{
  int temp = *n1;
  *n1 = *n2;
  *n2 = temp;
  
}
int main() {
    int n1 = 20;
    int n2 = 68;
    printf("The numbers before swapping n1 and n2 %d %d \n",n1, n2);
    swap(&n1, &n2);
    printf("The numbers after swapping n1 and n2 %d %d",n1, n2);
    return 0;
}

RELATED TAGS

c
communitycreator

CONTRIBUTOR

Divyanjali Vallapu Reddy
RELATED COURSES

View all Courses

Keep Exploring