C Parameter Passing: Pass-by-Value vs Pass-by-Address (Pointers)
Welcome to Phase 6 (Chapter 12): C Parameter Passing โ Pass-by-Value vs Pass-by-Address Masterclass! In C, understanding how arguments travel across RAM memory into function boundaries is the foundational secret to mastering pointers and memory management. In this comprehensive guide, you will master the difference between Call by Value (isolated copies in separate stack frames) and Call by Address / Reference (in-place memory mutation via pointers), how to swap variables, and how functions can return multiple values through memory addresses.
By default, C functions use Pass by Value. When you pass a variable into a function, CPU creates a completely independent copy of that value inside the called function's new Stack Frame:
[ main() Stack Frame ] ---> x = 10, y = 20
โ (Copies values 10 and 20)
โผ
[ wrongSwap() Stack Frame ] ---> a = 10, b = 20 (Swaps a and b locally)
โ
โผ (wrongSwap finishes and its Stack Frame is DESTROYED!)
[ main() Stack Frame ] ---> x is STILL 10, y is STILL 20! (NO change in main)
Function caller's memory variables ni directly modify cheyyalante, value kakunda variable เฐฏเฑเฐเฑเฐ RAM Memory Address (&x) pass chesthamu. Function parameters lo pointer (int* a) tho aa address ni receive chesukuni, dereference operator (*a) tho direct ga main memory slot ni modify chesthundhi:
#include <stdio.h>
// 1. Pass by Value (Fails to modify caller's variables)
void wrongSwap(int a, int b) {
int temp = a; a = b; b = temp;
}
// 2. Pass by Address (Modifies caller's RAM memory directly!)
void realSwap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int x = 10, y = 20;
wrongSwap(x, y);
printf("After wrongSwap: x = %d, y = %d (Unchanged!)\n", x, y);
realSwap(&x, &y); // Passing memory addresses &x and &y
printf("After realSwap: x = %d, y = %d (Swapped!)\n", x, y);
return 0;
}
๐ก How to Return Multiple Values in C?
C functions can only return a single value via the return statement. Kaani Pass-by-Address use chesi, multiple variables addresses ni pass cheyyadam dwara, function single execution lo Multiple Outputs (e.g. Quotient and Remainder) ni caller ki return cheyyavachu!
Run this multi-result computation function (calculating Area and Perimeter simultaneously):
#include <stdio.h>
void getCircleMetrics(double radius, double* area, double* perimeter) {
*area = 3.14159 * radius * radius;
*perimeter = 2.0 * 3.14159 * radius;
}
int main(void) {
double r = 5.0, a, p;
getCircleMetrics(r, &a, &p);
printf("Circle (r=%.1f): Area = %.2f, Perimeter = %.2f\n", r, a, p);
return 0;
}