Call by Value and Call by Reference

 

Call by Value and Call by Reference

There are two ways to pass arguments/parameters to function calls:

  • Call by Value

  • Call by Reference

Major Difference

  • In call by value, a copy of actual arguments is passed to the function.

  • In call by reference, the location (address) of actual arguments is passed, so changes inside the function affect the original variables.


Call by Value in C

In C, all function arguments are passed by value.

  • The calling and called functions do not share memory.

  • Each function works on its own copy of variables.

  • The called function cannot directly modify variables of the calling function.

Why Call by Reference is Sometimes Needed

  1. A function can return only one value using the return statement.

    • If multiple values need to be modified, call by reference is required.

  2. If the data size is large, copying arguments:

    • Takes more time

    • Uses more memory


How Call by Reference Works in C

To achieve call by reference:

  • The calling function passes the address of the variable (using &).

  • The called function receives a pointer.

  • The variable is accessed using dereferencing (*).

  • Changes made through the pointer affect the original variable.


Comparison Table

Call by ValueCall by Reference
Copy of actual arguments is passed    Address of actual arguments is passed
Changes in function do not affect original variables    Changes do affect original variables
Safer — accidental modification is impossible    Must be handled carefully to avoid unexpected                 changes

Example: Call by Value

#include <stdio.h> void swapByValue(int a, int b) { int t; t = a; a = b; b = t; } int main() { int n1 = 10, n2 = 20; /* actual arguments will remain unchanged */ swapByValue(n1, n2); printf("n1: %d, n2: %d\n", n1, n2); }

Output

n1: 10, n2: 20

Explanation:
swapByValue() only swaps local copies a and b.
Original variables n1 and n2 remain unchanged.


Example: Call by Reference

#include <stdio.h> void swapByReference(int *a, int *b) { int t; t = *a; *a = *b; *b = t; } int main() { int n1 = 10, n2 = 20; /* actual arguments will be altered */ swapByReference(&n1, &n2); printf("n1: %d, n2: %d\n", n1, n2); }

Output

n1: 20, n2: 10

Explanation:
Addresses of n1 and n2 are passed.
The function modifies the original variables using pointers.


Important Note

Arrays are passed by reference in C.
Any modification made to an array inside a function affects the original array.

Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays