Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Saturday, 1 June 2019

Call by value vs Call by reference in C

 Following are the differences between a call by value and call by reference are:












Example of a call by value:

#include <stdio.h>  
void change(int,int);  
int main()  
{  
    int a=10,b=20;  
    change(a,b); //calling a function by passing the values of variables.  
   
 printf("Value of a is: %d",a);  
    printf("\n");  
    printf("Value of b is: %d",b);  
    return 0;  
}  
void change(int x,int y)  
{  
    x=13;  
    y=17;  
}  

Output:

Value of a is: 10
Value of b is: 20


Example of call by reference:

#include <stdio.h>  
void change(int*,int*);  
int main()  
{  
    int a=10,b=20;  
    change(&a,&b); // calling a function by passing references of variables.  

    printf("Value of a is: %d",a);  
    printf("\n");  
    printf("Value of b is: %d",b);  
    return 0;  
}  
void change(int *x,int *y)  
{  
    *x=13;  
    *y=17;  
}  

Output:

Value of a is: 13
Value of b is: 17

0 comments:

Post a Comment