Functions, Parameter Passing & Pass-by-Value vs Pointers
1Concept
In C, ALL function arguments are passed strictly by value (copied). To modify a caller's variable or pass large structs without copy overhead, developers pass pointer addresses (pass-by-pointer). Function declarations (prototypes) inform the compiler of parameter types and return values.
2Architecture Diagram
Pass-by-Value: Caller: [ x = 10 ] --Copy Val 10--> Callee: [ a = 10 ] (Modifying 'a' doesn't affect 'x') Pass-by-Pointer: Caller: [ x = 10 (Addr 0x1000) ] --Pass Addr 0x1000--> Callee: [ ptr = 0x1000 ] Dereferencing *ptr = 20 directly modifies Caller's 'x'!
3Code Example
Stage 0 Language Foundations
#include <stdio.h>
// Pass-by-value: caller's variable remains unchanged
void swap_by_value(int a, int b) {
int temp = a;
a = b;
b = temp;
}
// Pass-by-pointer: modifies caller's memory directly
void swap_by_pointer(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int x = 100, y = 200;
printf("Original: x = %d, y = %d\n", x, y);
swap_by_value(x, y);
printf("After swap_by_value: x = %d, y = %d (Unchanged!)\n", x, y);
swap_by_pointer(&x, &y);
printf("After swap_by_pointer: x = %d, y = %d (Swapped!)\n", x, y);
return 0;
}4Expected Output
Original: x = 100, y = 200 After swap_by_value: x = 100, y = 200 (Unchanged!) After swap_by_pointer: x = 200, y = 100 (Swapped!)
5Key Takeaways
- ✓C has no native pass-by-reference (&ref syntax in C++); it simulates it via pointers.
- ✓Use const T* ptr for input-only pointer parameters to guarantee caller data is read-only.
- ✓Never return a pointer to a local stack variable from a function (dangling pointer!).