1. What is Call by Value?
Call by Value is the default method C uses
to pass arguments to a function. This method is used for all basic data types
like int, float, char, and even
structures (struct).
Here is the most important rule:
In call by value, a copy of the argument's value is created and passed to the function's parameter. The parameter inside the function is a completely separate variable in memory from the original argument.
2. How it Works (Memory)
Imagine you have a variable a = 10; in your main function.
When you call myFunction(a), this is what happens:
1.
main has a
variable a at memory address 1000. Its
value is 10.
2.
The program calls myFunction.
3.
The function creates its own new parameter variable, x, at a
totally different memory address (e.g., 5000).
4.
The value from a (which
is 10) is copied into x.
5.
Now, x contains
10, but a and x are
two different variables at two different locations.
3. The Main Consequence
Because the function is only working with a copy, any changes made
to the parameter inside
the function have NO
EFFECT on the original argument back in the calling
function (like main).
This is a "safety" feature. The function cannot accidentally change your original data. But it's a problem if you *want* the function to change your data.
4. Example: The "Failed" Swap
The most famous example is trying to write a function that swaps two numbers. Using call by value, this attempt will fail to change the original numbers.
/* * Example 1: Call by Value (The "Failed Swap") * The changes inside swap() will NOT affect main().*/
#include <stdio.h>
// Prototype for our swap function
void swap(int x, int y);
int main() {
int a = 10;
int b = 20;
printf("[In main] Before swap: a = %d, b = %d\n", a, b);
// Call the swap function.
// A copy of 'a' (10) is given to 'x'.
// A copy of 'b' (20) is given to 'y'.
swap(a, b);
printf("[In main] After swap: a = %d, b = %d\n", a, b);
// The values are STILL 10 and 20!
return 0;
} /* * This function's parameters 'x' and 'y' are * COPIES of 'a' and 'b'.*/
void swap(int x, int y) {
int temp;
printf(" [In swap] Received: x = %d, y = %d\n", x, y);
// This swaps the COPIES
temp = x; x = y; y = temp; printf(" [In swap] Swapped copies: x = %d, y = %d\n", x, y);
}Expected Output:
[In main] Before swap: a = 10, b = 20
[In swap] Received: x = 10, y = 20
[In swap] Swapped copies: x = 20, y = 10
[In main] After swap: a = 10, b = 20
Analysis: Look
at the output! The swap function successfully swapped its own variables (x and y). But because x and y were just copies, the
original a and b in main were never touched and remained 10 and 20.