Lesson 23: Call by Value vs. Call by Reference (Introduction)
C primarily uses Call by Value, but we can simulate Call by Reference using pointers (introduced formally later).
1. Call by Value
When a variable is passed by value, the function receives a copy of the variable's value. Any modifications made to the parameter inside the function do not affect the original variable outside.
c #include <stdio.h>
void modify_value(int x) { x = x * 2; // Changes the COPY of 'a' printf("Inside function: x = %d\n", x); }
int main() { int a = 10; modify_value(a); printf("Outside function: a = %d\n", a); // a is still 10 return 0; }
Output:
Inside function: x = 20 Outside function: a = 10
2. The Need for Call by Reference (Preview)
What if we need a function to change the value of an external variable?
C achieves this by passing the variable's memory address (a pointer) instead of its value. When the function receives the address, it can look up and modify the original data location.
c // We will use pointers (*) and the address operator (&) here void swap_numbers(int *ptr_a, int *ptr_b); // ... later implementation uses pointers to modify memory ...
This technique is fundamental to C and will be fully explored when we cover Pointers (Module 6).