C Call By Value Vs Call By Reference Explanation And Examples

Call by Value
x = 10
Original
copy = 10
Copy passed

<strong>Result:</strong> Original unchanged

Call by Reference
x = 10
Original
&x (address)
Address passed

<strong>Result:</strong> Original modified

Let's explore call by value and call by reference in the C programming language separately.

Call by Value in C

In the call by value approach, the content of the real arguments gets duplicated into the formal parameters. Put differently, the variable's content is employed during the function invocation in the call by value technique. Changes to the formal parameter cannot alter the value of the real parameter in call by value. This method is commonly employed for basic data types like integers, characters, and floating-point numbers. It's the default behavior in the C programming language.

In a call by value scenario, separate memory locations are assigned for the actual and formal parameters because the value of the actual parameter is duplicated into the formal parameter. The actual parameter pertains to the argument employed during the function call, while the formal parameter corresponds to the argument specified in the function definition.

Syntax

It has the following syntax:

Example

[return type] functionName([type][parameter name],...).

C Call by Value Example

Let's explore the idea of call by value in the C programming language using the following example:

Example

Example

#include<stdio.h>

void change(int num) {  

    printf("Before adding value inside function num=%d \n",num);  

    num=num+100;  

    printf("After adding value inside function num=%d \n", num);  

}  

int main() {  

    int x=100;  

    printf("Before function call x=%d \n", x);  

    change(x);//passing value in function  

    printf("After function call x=%d \n", x);  

return 0;

}

Output:

Output

Before function call x=100

Before adding value inside function num=100

After adding value inside function num=200

After function call x=100

Explanation:

In this illustration, we showcase the concept of call by value, where the function change receives a duplicate of the variable x. Modifications to num within the function do not impact the original x variable in the main function. As a result, the value of x remains unaltered following the function invocation.

Call by Value Example to swap the values of the two variables

Let's consider another example to demonstrate call by value when swapping the values of two variables.

Example

Example

#include <stdio.h>

void swap(int , int); //prototype of the function 

int main()

{

    int a = 10;

    int b = 20; 

    printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main

    swap(a,b);

    printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not change by changing the formal parameters in call by value, a = 10, b = 20

}

void swap (int a, int b)

{

    int temp; 

    temp = a;

    a=b;

    b=temp;

    printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b = 10 

}

Output:

Output

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 10, b = 20

Explanation:

In this instance, we illustrate the concept of call by value, where the swap function is provided with duplicates of a and b. Subsequently, the swapping occurs exclusively within the function, ensuring that the initial values in the main function are unaffected following the function invocation.

Features of call by value in C

There are several features of call by value in C. Some main features of call by value in C are as follows:

  • Data isolation: The basic value remains preserved and unchanged.
  • Safe and Predictable: Since the function cannot modify the original variable, it becomes easy to reason about the code.
  • Memory overhead: For large data types or structures , copying may include additional memory and performance costs.
  • Use case: It is preferred when the intention is to only use the input without modifying it.
  • Call by Reference in C

In pass by reference, we provide the memory address (reference) of the original parameter to the function rather than passing a duplicate of the variable. This enables the function to access and alter the original variables directly.

In pass by reference, both the formal parameters and actual parameters share the same memory allocation. The function operations manipulate the value stored at the address of the given parameters, and any changes are reflected at that same address. While C lacks native call by reference support (unlike C++), it can be emulated through the use of pointers.

Syntax of Call by Reference in C

It has the following syntax:

Example

[return type] functionName([type]* [parameter name],...).

C Call by Reference Example

Let's consider a scenario to demonstrate the concept of passing arguments by reference in the C programming language.

Example

Example

#include<stdio.h>

void change(int *num) {  

    printf("Before adding value inside function num=%d \n",*num);  

    (*num) += 100;  

    printf("After adding value inside function num=%d \n", *num);  

}    

int main() {  

    int x=100;  

    printf("Before function call x=%d \n", x);  

    change(&x);//passing reference in function  

    printf("After function call x=%d \n", x);  

return 0;

}

Output:

Output

Before function call x=100

Before adding value inside function num=100

After adding value inside function num=200

After function call x=200

Explanation:

In this illustration, we showcase the concept of call by reference through pointers. Subsequently, we utilize the memory address of x that is supplied to the change function, enabling direct alteration of its value. Consequently, modifications performed within the function are mirrored in the main function, leading to x being updated to 200 post the function invocation.

Call by Reference Example to swap the values of the two variables

Let's consider an instance to demonstrate how to exchange the values of two variables using call by reference in the C programming language.

Example

Example

#include <stdio.h>

void swap(int *, int *); //prototype of the function 

int main()

{

    int a = 10;

    int b = 20; 

    printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main

    swap(&a,&b);

    printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do change in call by reference, a = 10, b = 20

}

void swap (int *a, int *b)

{

    int temp; 

    temp = *a;

    *a=*b;

    *b=temp;

    printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b = 10 

}

Output:

Output

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 20, b = 10

Explanation:

In the provided illustration, we showcase the concept of call by reference utilizing pointers. Following this, the memory addresses of variables a and b are transferred to the swap function, enabling the interchange of their respective values. Consequently, the modifications are retained within the main function, resulting in a being set to 20 and b being set to 10.

Features of Call by Reference in C

There are several features of call by reference in C. Some main features are as follows:

  • Direct Modification: The function can change the real variable value.
  • Efficient to large data: Instead of mimicking large structures or arrays, references allow better performance.
  • Complexity and Risk: The use of urban indicator can cause bugs or memory issues.
  • Use Case: When the function must modify inputs or return multiple values.
  • When to use Call by Value and Call by Reference in C

In C language, the decision between Call by Value and Call by Reference is crucial for optimizing code performance and ensuring its accuracy. Various scenarios exist where either Call by Value or Call by Reference can be applied in C. Here are some key situations:

Call by Value

Call by Value can be utilized when:

  • We want to protect the original variable from modification.
  • The function only needs to read the data, not modify it.
  • We are working with small data types, such as integers or characters, where copying is cheap.
  • Call by Reference

Call by Reference can be utilized when:

  • We need to modify the original variable from within the function.
  • We are working with large data structures (such as arrays, structures) to avoid unnecessary imitations.
  • We need a function to return several values using pointers.
  • Performance is a priority, and memory efficiency is required.
  • We are manipulating an object-like behaviour or dynamic memory.

For instance, Call by Reference delivers efficiency and adaptability in sorting algorithms, input/output tasks, and real-time modifications. Conversely, Call by Value ensures security and transparency for immutable operations such as verifying validity or status.

Difference between Call by Value and Call by Reference in C

There exist various variances between call by value and call by reference in the C programming language. A few key disparities are outlined below:

Call by Value Call by Reference
A copy of the value is passed into the function. An address of value is passed into the function.
Changes made inside the function are limited to the function only. The values of the actual parameters do not change by changing the formal parameters. Changes made inside the function validate outside of the function also. The values of the actual parameters do change by changing the formal parameters.
Actual and formal arguments are created at the different memory locations. Actual and formal arguments are created at the same memory location.
Data is safe because the original data is protected from unintended changes. Data is risky if not handled properly because the original data can be modified.
It is used when we want to read or simulate data without modifying it. It is used when we need to modify or update the original variable.
It may be slower if large data is copied repeatedly. It is more efficient for large structures (like arrays or structs).
It is simple to implement and understand. It is slightly more complex due to pointers.
It performs several simple operations, including mathematical simulations, comparisons, etc. It performs several operations, such as depositing money, updating marks, modifying records, etc.

Conclusion

In summary, it is essential to grasp the distinction between call by value and call by reference in C programming to develop effective code. Call by value offers a secure method for passing variables to functions without altering their initial state. Conversely, call by reference is beneficial for tasks that involve directly modifying external variables, like updating values, altering arrays, or manipulating structures.

Input Required

This code uses input(). Please provide values below: