Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / C Programming Tutorial / Chapter 3: Functions, Arrays & Pointers
C ⏱ 12 min read

Functions: Call by Value vs Call by Reference

Understanding how functions pass data in C reveals how memory addresses and stacks operate in hardware.

What is it?

A function is a named block of code that performs a specific task. • Call by Value: Copies the value of the argument into the parameter. • Call by Reference (via Pointers): Passes the memory address of the argument so the function can modify original caller variables.

Why is it used?

Modularity, code reuse, and modifying variables outside the current stack frame.

Detailed Explanation

In pure C, everything is technically passed by value. When we say 'Call by Reference', we mean passing a pointer (the memory address) by value. • Call by Value: Changes inside the function do NOT affect original caller variables. • Call by Reference: By passing `&var` into a pointer parameter `*ptr`, the function can dereference the pointer `*ptr = newValue;` to mutate the caller's variable in place.

Syntax Structure

Syntax Blueprint
// Call by value
void func(int x);

// Call by reference
void swap(int *x, int *y);

Code Example

C Code
#include <stdio.h>

// 1. Call by Value (Fails to swap caller variables)
void swap_by_value(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
}

// 2. Call by Reference using Pointers (Successfully swaps caller variables)
void swap_by_reference(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    int x = 10, y = 20;
    
    printf("Initial:          x = %d, y = %d\n", x, y);
    
    swap_by_value(x, y);
    printf("After By-Value:   x = %d, y = %d (Unchanged!)\n", x, y);
    
    swap_by_reference(&x, &y); // Pass memory addresses with &
    printf("After By-Ref:     x = %d, y = %d (Swapped!)\n", x, y);
    
    return 0;
}

Explanation of the Code

• `swap_by_value` only changes its local stack frame copies. • `swap_by_reference(&x, &y)` sends the actual memory addresses of x and y. • `*a = *b` dereferences the pointer, overwriting the value in `main`'s memory space.

Expected Output

Initial: x = 10, y = 20 After By-Value: x = 10, y = 20 (Unchanged!) After By-Ref: x = 20, y = 10 (Swapped!)

Real-World Application

This is how functions like `scanf("%d", &var)` write input into your variables.

Common Mistakes to Avoid

• Passing variables without `&` when calling pointer functions (`swap(x, y)` instead of `swap(&x, &y)`). • Dereferencing uninitialized or NULL pointers (causes crashes).

Quick Practice Challenge

Write a function `double_in_place(int *num)` that doubles the value of an integer through its pointer.

Key Takeaways

• Call by Value passes copies of arguments. • Call by Reference passes memory addresses via pointers. • Use `*ptr` to dereference and modify original values.