MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

Call By Value

In C programming, the call by value mechanism is used to pass arguments to functions. When a function is called by value, a copy of the actual argument's value is made and passed to the function. This means that the function operates on a copy of the variable, not on the original variable itself.

Example

Here's a simple example to illustrate call by value:

#include <stdio.h>
// Function that takes an integer argument by value void modifyValue(int x) { x = x + 10; // Modify the copy of the value printf("Inside function: x = %d\n", x); } int main() { int a = 5; printf("Before function call: a = %d\n", a); modifyValue(a); // Pass the value of 'a' to the function printf("After function call: a = %d\n", a); // 'a' is unchanged return 0; }

Output

Before function call: a = 5 Inside function: x = 15 After function call: a = 5


Explanation

  • a is passed to modifyValue function.
  • Inside modifyValue, x is a copy of a. Modifying x does not affect a in main.
  • The original variable a remains unchanged outside the function.


Advantages

  1. Safety: The original values of the arguments cannot be altered by the function. This ensures that the caller’s data is protected from unintended modifications.
  2. Simplicity: Call by value is straightforward and easier to understand because it operates on copies of the values.

Report an issue

Reporting: Call By Value (topic)

Related Posts