pass by value in functions in c

29 Dec 2022 Balmiki Kumar 0 C Programming

Pass by Value in C Functions: Exploring Value-Based Parameter Passin

Pass by Value: In this method, the value of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. In pass-by-value, the changes made to formal arguments in the called function do not affect the values of actual arguments in the calling function.

Pass by value" is a mechanism used by functions in C to pass arguments to a function. When an argument is passed by value, a copy of its value is created and passed to the function, rather than a reference to the original value. This means that any changes made to the argument inside the function do not affect the original value outside the function.

In C, all primitive data types (such as int, char, and float) are passed by value by default. When a function is called with a primitive data type argument, a copy of the value is passed to the function, which is stored in a new memory location allocated for the function call.

Understanding Pass by Value in C Functions: Explained with Examples

#include
void swap(int x, int y) {
 int t;
 t = x;
 x = y;
 y = t;
}
int main() {
 int m = 10, n = 20;
 printf("Before executing swap m=%d n=%d\n", m, n);
 swap(m, n);
 printf("After executing swap m=%d n=%d\n", m, n);
 return 0;
}

Output:

Before executing swap m=10 n=20
After executing swap m=10 n=20
 

Explanation:

In the main function, value of variables m, n are not changed though they are passed to function 'swap'. Swap function has a copy of m, n and hence it can not manipulate the actual value of arguments passed to it.

Example 02, consider the following code

void increment(int x) {
    x++;
}

int main() {
    int a = 5;
    increment(a);
    printf("%d\n", a);
    return 0;
}

Attention: In this code, the increment function takes an integer argument x, which is passed by value. Inside the function, the value of x is incremented, but since it is passed by value, this change does not affect the original value of a in main(). Therefore, the output of this program is 5.

Passing arguments by value has the advantage of being simple and efficient, but it can also make it more difficult to modify variables outside of the function. If you want to modify a variable outside of a function, you may need to pass a pointer to the variable instead, which is known as passing by reference.

BY: Balmiki Kumar

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.