Join Whatsapp Channel for Ignou latest updates JOIN NOW

Briefly discuss the concept of “Call by value” and “Call by reference”. Give example code in C for each. Support your code with suitable comments

“Call by value” and “Call by reference” are two different ways to pass arguments to functions in programming.

Call by Value

In “call by value”, a copy of the actual parameter’s value is passed to the function. This means that any changes made to the parameter inside the function do not affect the original variable.

Example in C:

#include <stdio.h>

// Function that takes an integer by value
void callByValue(int x) {
    // Modify the parameter
    x = 100;
    printf("Inside callByValue, x = %d\n", x);
}

int main() {
    int a = 10;
    printf("Before callByValue, a = %d\n", a);

    // Call the function with 'a' as argument
    callByValue(a);

    // 'a' is not modified by the function
    printf("After callByValue, a = %d\n", a);

    return 0;
}

Output:

Before callByValue, a = 10
Inside callByValue, x = 100
After callByValue, a = 10

Call by Reference

In “call by reference”, the address of the actual parameter is passed to the function, allowing the function to modify the original variable directly.

Example in C:

#include <stdio.h>

// Function that takes a pointer to an integer (call by reference)
void callByReference(int *x) {
    // Modify the value at the address pointed to by 'x'
    *x = 100;
    printf("Inside callByReference, *x = %d\n", *x);
}

int main() {
    int a = 10;
    printf("Before callByReference, a = %d\n", a);

    // Call the function with the address of 'a' as argument
    callByReference(&a);

    // 'a' is modified by the function
    printf("After callByReference, a = %d\n", a);

    return 0;
}

Output:

Before callByReference, a = 10
Inside callByReference, *x = 100
After callByReference, a = 100

Explanation

  • Call by Value: The function callByValue receives a copy of the variable a. Any changes made to x inside the function do not affect a in the main function.
  • Call by Reference: The function callByReference receives a pointer to the variable a. The function can modify the actual value of a by dereferencing the pointer x (using *x).

These examples demonstrate how each method passes arguments to functions and how modifications within the function affect the original variables.

error: Content is protected !!