Call by Value and Call by Reference in C
×


Call by Value and Call by Reference in C

120

Call by Value in C 

In Call by Value in C, the value of actual parameters will be copied to formal parameters in different locations.

Actual parameters: The parameters passed to the function are called actual parameters.

Formal parameters: parameters are like placeholders for values that a function expects to receive when it's called. They represent the input values that the function will work with.

Syntax of Call by Value in C 

void function name(datatype parameter name){
//Function body
}

Example:

// Program for call by value in C
#include<stdio.h>

// Function to increment the value by 1 (though it doesn't affect the main variable)
void increment(int i){
    i++;
}

int main()
{
    int A = 10; // Declare and initialize variable A with value 10
    
    increment(A); // Call the increment function with A
    
    printf("The value of A after call by value : %d\n", A); // Print the value of A
    
    return 0; // Return 0 to indicate successful execution
}
Output:

value of A after call by value: 10

Call by Reference in C 

In Call by Reference in C instead of passing a copy of the value, the address of actual parameters is passed to the Function.

Actual parameters and formal parameters refer to the same memory location.

 Hence, alterations made to the formal parameters will impact the actual parameters.

Syntax of Call by Reference in C 

void function name(datatype * parameter name){
// function body
}
Example:

// Program for call by Reference in C
#include<stdio.h>

// Function to increment the value pointed to by i
void increment(int *i){
    (*i)++;  // Increment the value at the address pointed by i
}

int main()
{
    int A = 10;  // Declare and initialize variable A with value 10
    
    increment(&A);  // Call the increment function with the address of A
    
    printf("value of A after call by reference: %d\n", A);  // Print the value of A
    
    return 0;  // Return 0 to indicate successful execution
}
Output:

value of A is after call by reference: 11


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments