Nearby lessons
47 of 72C - Call by Value
Call by Value is a fundamental concept in C programming. This tutorial explains how functions receive copies of variable values, why changes inside a function do not affect the original variables, and how to demonstrate this concept using a swap example. It also includes clear explanations, common mistakes, and exam-style MCQs.
Call by Value
Meaning of Call by Value
Definition: Call by value is a method of passing arguments to a function in which the function receives a copy of each argument's value.
In C, when we pass a variable to a function, its value is copied into the function parameter. Any changes made to that parameter affect only the local copy, not the original variable declared in main().
How Does Call by Value Work?
- Declare two variables, a and b, in the main() function.
- Pass their values to the swap() function.
- The function receives copies of those values in x and y.
- The function swaps the copied values using a temporary variable.
- After the function finishes, the original variables a and b remain unchanged.
Example: Swapping Two Numbers
Swapping means exchanging the values of two variables. In this example, a is 10 and b is 20. The swap() function receives copies of these values and swaps only its local parameters.
Understanding the Code
- swap(int x, int y): The function receives copies of the integer values.
- int temp = x: Saves the value of x in a temporary variable.
- x = y: Copies the value of y into x.
- y = temp: Copies the saved value into y.
- main(): The original values of a and b remain unchanged because the function modifies only its local copies.
Common Mistakes in Call by Value
1. Expecting Original Variables to Change
Calling swap(a, b) passes copies of the values. Swapping those copies does not change a and b in main().
2. Confusing Actual and Formal Parameters
The variables a and b are actual arguments in the function call. The parameters x and y receive copies of their values.
3. Thinking the Function Cannot Modify Its Parameters
A function can modify its local parameters. However, those modifications do not affect the original variables when ordinary values are passed.
4. Confusing Call by Value with Pointer-Based Modification
To modify original variables, C programmers commonly pass their addresses to a function and use pointers to access the original values. This technique is demonstrated in the Call by Reference tutorial.
- Call by value means passing a copy of a variable value to a function.
- Changes made to a copied parameter do not affect the original variable.
- Actual arguments are supplied when a function is called.
- Formal parameters receive the argument values inside the function.
- Swapping values inside a call-by-value function does not swap the original variables.
- C always passes function arguments by value.
- Pointers can be used to modify original variables through their addresses.