In C programming, pointers are powerful tools that allow direct access to memory addresses. They are essential for dynamic memory management, arrays, and efficient function calls. This post introduces pointers and explains the key difference between Call by Value and Call by Reference with simple examples.
What is a Pointer in C?
A pointer is a variable that stores the memory address of another variable.
Syntax:
int *ptr; // declares a pointer to an integer
*
is used to declare a pointer and also to dereference it.&
is used to get the address of a variable.
Example: Simple Pointer
#include <stdio.h>
int main() {
int x = 10;
int *ptr = &x;
printf("Value of x: %d\n", x);
printf("Address of x: %p\n", &x);
printf("Pointer holds: %p\n", ptr);
printf("Value at pointer: %d\n", *ptr);
return 0;
}
Call by Value in C
In Call by Value, a copy of the variable is passed to the function. Changes made inside the function do not affect the original value.
Example:
#include <stdio.h>
void update(int a) {
a = a + 10;
}
int main() {
int num = 5;
update(num);
printf("After call by value: %d\n", num); // Output: 5
return 0;
}
Here, num
remains unchanged.
Call by Reference in C
In Call by Reference, the address of the variable is passed. Changes made inside the function affect the original value.
Example:
#include <stdio.h>
void update(int *a) {
*a = *a + 10;
}
int main() {
int num = 5;
update(&num);
printf("After call by reference: %d\n", num); // Output: 15
return 0;
}
Here, the original num
value changes because the function received its memory address.
Key Differences
Feature | Call by Value | Call by Reference |
---|---|---|
Passes | Copy of variable | Address of variable |
Modifies Original | ❌ No | ✅ Yes |
Memory Use | More | Less |
Use Case | Safe, simple | Efficient, powerful |
Key Takeaways
- Pointers are essential for advanced C programming.
- Call by value is safer but doesn’t modify original data.
- Call by reference uses pointers to modify values directly.
- Efficient memory management is possible with pointer usage.
Conclusion
Understanding pointers and the distinction between Call by Value and Call by Reference is vital for mastering C. These concepts not only improve performance but also help in handling complex data structures like arrays, linked lists, and trees.
Start practicing with simple examples, and you’ll soon grasp the power and flexibility pointers bring to your code!