C Call by Value and Call by Reference

There are two ways to pass arguments to a function.

Call by value

A copy of the value is sent. Changes inside the function do not change the original variables. C uses this way by default.

#include <stdio.h>

void swap(int a, int b) {
    int t = a;
    a = b;
    b = t;
}

int main(void) {
    int x = 10, y = 20;
    swap(x, y);
    printf("x=%d y=%d\n", x, y);
    return 0;
}

Output:

Output of the above program is

x=10 y=20

The values did not swap, because the function worked on copies.

Call by reference (using pointers)

We send the address of the variables with &. The function uses pointers (*) to change the original values.

#include <stdio.h>

void swap(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main(void) {
    int x = 10, y = 20;
    swap(&x, &y);
    printf("x=%d y=%d\n", x, y);
    return 0;
}

Output:

Output of the above program is

x=20 y=10

Difference

PointCall by valueCall by reference
What is sentCopy of the valueAddress of the variable
Original changed?NoYes
MemoryExtra copy is madeNo copy of the data
Note: Strictly speaking, C has only call by value. Passing a pointer is also a value (the address), but it gives the same result as call by reference. Learn more in Pointers.

Next: C Recursion.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a C program to find the factorial of a number using recursion
Write a C program to swap two numbers using a function and pointers
Interview Questions & Answers
What is the difference between call by value and call by reference in C?
What is recursion in C?
What is the difference between local and global variables in C?
What are storage classes in C?
What is the use of the static keyword in C?