type of function

There are two types of function:


A: call by value
B: call by reference

Call By Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of caller.


// C program to illustrate 
// call by value 

#include <stdio.h>
#include<conio.h> 

// Function Prototype 
void swapx(int x, int y); 

// Main function 
int main() 
int a = 10, b = 20; 

// Pass by Values 
swapx(a, b); 

printf("a=%d b=%d\n", a, b); 

return 0; 

// Swap functions that swaps 
// two values 
void swapx(int x, int y) 
int t; 

t = x; 
x = y; 
y = t; 

printf("x=%d y=%d\n", x, y); 
Output:
x=20 y=10
a=10 b=20


Call by Reference: Both the actual and formal parameters refer to same locations, so any changes made inside the function are actually reflected in actual parameters of caller.


// C program to illustrate 
// Call by Reference 

#include <stdio.h> 

// Function Prototype 
void swapx(int*, int*); 

// Main function 
int main() 
int a = 10, b = 20; 

// Pass reference 
swapx(&a, &b); 

printf("a=%d b=%d\n", a, b); 

return 0; 

// Function to swap two variables 
// by references 
void swapx(int* x, int* y) 
int t; 

t = *x; 
*x = *y; 
*y = t; 

printf("x=%d y=%d\n", *x, *y); 
Output:
x=20 y=10
a=20 b=10



CALL BY VALUECALL BY REFERENCE
While calling a function, we pass values of variables to it. Such functions are known as “Call By Values”.While calling a function, instead of passing the values of variables, we pass address of variables(location of variables) to the function known as “Call By References.
In this method, the value of each variable in calling function is copied into corresponding dummy variables of the called function.In this method, the address of actual variables in the calling function are copied into the dummy variables of the called function.
With this method, the changes made to the dummy variables in the called function have no effect on the values of actual variables in the calling function.With this method, using addresses we would have an access to the actual variables and hence we would be able to manipulate them

0 Comments:

Post a Comment