← Previous | 🏠 Homepage | Next Chapter → |
Call by Value vs Call by Reference (With Pointer Magic!)
Call by Value – “Copy Paste”
sum = calsum(a, b, c);
You're actually saying:
"Hey function! Take copies of my values and play with them. But don’t touch the originals!"
Example:
main() {
int a = 10, b = 20;
swapv(a, b);
printf("a = %d, b = %d", a, b);
}
swapv(int x, int y) {
int t = x;
x = y;
y = t;
printf("x = %d, y = %d", x, y);
}
Output:
x = 20, y = 10
a = 10, b = 20
Call by Reference – “Handle with Care (and Address)”
Now instead of sending copies, you send the actual address where the data lives!
main() {
int a = 10, b = 20;
swapr(&a, &b);
printf("a = %d, b = %d", a, b);
}
swapr(int *x, int *y) {
int t = *x;
*x = *y;
*y = t;
}
Output:
a = 20, b = 10
Success! Real values got swapped!
Why? Because *x
means "value at the address" — it’s like having the home key instead of a photo.
Meet the Pointer – C’s Favorite Trick
"Hey! I know where the real data lives!"
int i = 3;
int *j; // j will point to an int
j = &i; // j now holds the address of i
So...
-
i
is the real value (3) -
&i
is the address of i (say 65524) -
j
holds that address -
*j
means: go to that address and get the value = 3
So *j == i
. Magic? Nah, just pointers!
Pointer in a Pointer? YES!
int i = 3;
int *j = &i;
int **k = &j;
-
i
is 3 -
j
holds address ofi
-
k
holds address ofj
So:
-
*k
→ value ofj
→ address ofi
-
**k
→ value at address stored inj
→ value ofi
→ 3
It’s like asking your friend to ask another friend where your secret cookie stash is.
Mixing Value + Reference: Return More Than One Thing!
C normally lets you return only 1 value from a function.
But what if we want 2 or more? Use pointers!
main() {
int r = 5;
float area, peri;
areaperi(r, &area, &peri);
printf("Area = %f, Perimeter = %f", area, peri);
}
areaperi(int r, float *a, float *p) {
*a = 3.14 * r * r;
*p = 2 * 3.14 * r;
}
Boom! One function, two results returned using addresses!
It's like sending two containers and asking the function to fill them.
No comments:
Post a Comment