02. Parameters: Pass-by-Value vs Pointer Reference Mutation
🟡 Difficulty: Intermediate | Parameter Passing Mechanics, Memory Copying & Pointer Indirection
📖 Definition
In C, all parameters are strictly passed by value. Passing a variable to a function copies its data onto the function's local call stack frame. To simulate pass-by-reference (allowing a function to mutate a variable in the caller's stack frame), the caller passes the memory address pointer of the variable (e.g., &var), and the function dereferences it via pointer indirection (*ptr).
🎯 Why It Is Used
- Caller State Mutation: Modifying caller variables directly (e.g.
swap(&a, &b)or updating multi-field structs). - Returning Multiple Results: C functions can return only one value via
return; passing pointers allows functions to populate multiple output parameters. - Large Struct Copying Avoidance: Passing a pointer (8 bytes) to a 1000-byte
structavoids copying huge stack payloads.
⚙️ How It Works: Stack Copy vs Pointer Dereferencing
When calling func(x), a 4-byte or 8-byte copy of x's value is pushed onto the new stack frame. Modifying x inside func changes only the stack copy. When calling func(&x), the address of x is copied. Dereferencing *ptr = 100 resolves directly to x's original RAM location in the caller's stack frame.
📝 Syntax
// 1. Pass-by-Value (Copy - Caller variable unchanged)
void modify_copy(int num) {
num = 100; // Changes only local stack copy!
}
// 2. Simulated Pass-by-Reference (Pointer Mutation)
void modify_original(int *ptr) {
if (ptr != NULL) {
*ptr = 100; // Mutates caller's original RAM location!
}
}
🔀 Pass-by-Value vs Pointer Reference Comparison
| Passing Mechanism | What Is Pushed to Stack? | Can Function Mutate Caller Variable? | Memory Overhead |
|---|---|---|---|
| Pass-by-Value | Full copy of variable value | ❌ No (Local copy mutated) | Copies full byte size of data type |
| Pointer Pass-by-Ref | Copy of memory address (pointer) | ✅ Yes (Via *ptr dereference) |
Always 8 bytes (64-bit address) |
| Const Pointer Parameter | Copy of memory address (read-only) | ❌ No (Guarded by const) |
Always 8 bytes (prevents struct copy) |
🌱 Beginner Example: The Classic Swap Problem
#include <stdio.h>
// Failed Swap: Pass-by-Value
void swap_failed(int a, int b) {
int temp = a;
a = b;
b = temp;
}
// Successful Swap: Pointer Pass-by-Reference
void swap_successful(int *a, int *b) {
if (a != NULL && b != NULL) {
int temp = *a;
*a = *b;
*b = temp;
}
}
int main(void) {
int x = 10, y = 20;
swap_failed(x, y);
printf("After swap_failed : x = %d, y = %d (Unchanged!)\n", x, y);
swap_successful(&x, &y);
printf("After swap_successful: x = %d, y = %d (Swapped!)\n", x, y);
return 0;
}
🌼 Intermediate Example: Multiple Return Parameters
#include <stdio.h>
#include <stdbool.h>
// Returns success status, populates quotient and remainder via pointers
bool safe_divide(int dividend, int divisor, int *out_quotient, int *out_remainder) {
if (divisor == 0 || out_quotient == NULL || out_remainder == NULL) {
return false; // Division error
}
*out_quotient = dividend / divisor;
*out_remainder = dividend % divisor;
return true;
}
int main(void) {
int q, r;
if (safe_divide(17, 5, &q, &r)) {
printf("17 / 5 => Quotient: %d, Remainder: %d\n", q, r);
} else {
printf("Division error encountered!\n");
}
return 0;
}
🌲 Advanced Example: Efficient Struct Mutation & Read-Only Const Pointers
#include <stdio.h>
typedef struct {
int user_id;
double account_balance;
char tier;
} UserAccount;
// Fast Read-Only Access: Avoids copying struct, prevents accidental field mutation
void display_account(const UserAccount *acc) {
if (acc != NULL) {
printf("ID: %d | Balance: $%.2lf | Tier: %c\n",
acc->user_id, acc->account_balance, acc->tier);
}
}
// In-Place Mutation: Modifies caller's struct directly
void apply_bonus(UserAccount *acc, double bonus_amount) {
if (acc != NULL && bonus_amount > 0) {
acc->account_balance += bonus_amount;
}
}
int main(void) {
UserAccount user = {8841, 1200.00, 'Gold'};
display_account(&user);
apply_bonus(&user, 300.50);
printf("--- After Bonus ---\n");
display_account(&user);
return 0;
}
🔍 Line-by-Line Explanation
void swap_successful(int *a, int *b): Accepts pointer memory addresses of two integers.int temp = *a; *a = *b; *b = temp;: Dereferences pointers to read and modify original variables in caller's stack frame.bool safe_divide(..., int *out_quotient, ...): Populates output results through output pointers.void display_account(const UserAccount *acc): Usesconstpointer to read struct fields via arrow operatoracc->user_idwithout copying the struct.
💻 Expected Terminal Output
After swap_failed : x = 10, y = 20 (Unchanged!)
After swap_successful: x = 20, y = 10 (Swapped!)
17 / 5 => Quotient: 3, Remainder: 2
ID: 8841 | Balance: $1200.00 | Tier: G
--- After Bonus ---
ID: 8841 | Balance: $1500.50 | Tier: G
⚠️ Common Mistakes & Pitfalls
- Forgetting
&Address Operator at Call Site: Callingswap_successful(x, y)passes integers instead of addresses, causing compiler type errors or crashes. - Dereferencing Null Pointers inside Functions: Attempting
*ptr = 100without checkingif (ptr != NULL)leads to segmentation faults. - Returning Pointers to Local Stack Variables: Returning
&local_varfrom a function is a dangling pointer bug because the local stack frame is destroyed upon return!
📌 Important Rules & Limitations
- All parameter passing in C is strictly pass-by-value. Pass-by-reference is simulated by passing pointer addresses by value.
- Always check pointer parameters for
NULLbefore dereferencing.
🌐 Multilingual Explanation: English
C strictly passes arguments by value. To allow a function to modify caller variables, pass memory address pointers (&var) and dereference them (*ptr) inside the function.
🌐 Multilingual Explanation: Hindi (Roman Script)
C mein saare arguments pass-by-value hote hain. Agar aap chahte hain ki function main variable ki value change kare, toh variable ka address &var pass karein aur function ke andar *ptr se value modify karein.
🌐 Multilingual Explanation: Marathi (Roman Script)
C madhye sagle arguments pass-by-value hotat. Caller function madhil variable badalnyasathi address &var pass kara aani function madhye *ptr vapra.
❓ Practice Questions
- Why does
swap_failed(int a, int b)fail to swap variables in the main function? - How do pointer parameters allow a C function to return multiple results?
- Why is returning the address of a local automatic stack variable dangerous?
🚀 Practical Coding Challenge
Write a C program named min_max_finder.c with a function void find_min_max(const int arr[], size_t size, int *out_min, int *out_max) that iterates through an array and assigns the minimum and maximum values via output pointers.
🧭 Navigation & Breadcrumbs
← Previous: 01. Function Prototypes | Module 08 Guide | Next: 03. Recursion & Call Stack →