Call by value and Call by reference in c




Call by Value and Call by Reference in C



Call by Value and Call by Reference in C




Table of Contents



  1. Introduction

  2. Call by Value

    • Explanation

    • Example Program



  3. Call by Reference

    • Explanation

    • Example Program



  4. Difference Between Call by Value and Call by Reference

  5. Conclusion




Introduction


In C programming, when passing arguments to functions, there are two common ways: call by value and call by reference. Understanding the difference between these two methods is crucial for efficient and correct programming. This post will discuss call by value and call by reference in C, including their types, example programs, and differences.




Call by Value


Explanation


In call by value, a copy of the actual arguments is passed to the function. Any changes made to the parameters within the function do not affect the original variables outside the function. It is the default behavior in C when passing arguments to functions.



Example Program




#include <stdio.h>

void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}

int main() {
int x = 10, y = 20;
printf("Before Swap: x = %d, y = %d\n", x, y);
swap(x, y);
printf("After Swap: x = %d, y = %d\n", x, y);
return 0;
}




Call by Reference


Explanation


In call by reference, the memory address of the actual arguments is passed to the function. Any changes made to the parameters within the function will affect the original variables outside the function.



Example Program




#include <stdio.h>

void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x = 10, y = 20;
printf("Before Swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After Swap: x = %d, y = %d\n", x, y);
return 0;
}




Difference Between Call by Value and Call by Reference























Aspect Call by Value Call by Reference
Argument Passing A copy of the actual arguments is passed. The memory address of the actual arguments is passed.
Effect on Original Variables Changes made to parameters do not affect the original variables. Changes made to parameters affect the original variables.
Default Behavior Default behavior in C when passing arguments. Requires explicit use of pointers for passing arguments by reference.



Conclusion


Call by value and call by reference are two essential concepts in C programming when it comes to passing arguments to functions. Call by value is used to prevent changes to the original variables, while call by reference allows modifications to the original variables. Understanding these concepts will help you write efficient and robust C programs.





Post a Comment

0 Comments