Bypassing the reference
When parameters are passed to the function by reference, then the formal parameters become references (or aliases) to the actual parameters in the calling function. This means that (in this method) the called function does not create its own copies of original values, rather it works/refers to the original values by different names i.e. their references. Thus the called function works with the original data and any changes in the values gets reflected to the data in the calling function.
The call by reference method is useful in the situations where the values of the original variables are to be changed using a function.
Example:1
//to swap two values by passing reference #include<stdio.h> #include<conio.h> void swap(int &p,int &q); int main() { int a,b; printf("Enter 2 numbers "); scanf("%d %d",&a,&b); swap(a,b); printf("in main function\n"); printf("1st value %d 2nd value %d\n",a,b); getch(); return(0); } void swap(int &p,int &q) { int t; t=p;//1 p=q;//2 q=t;//3 }
/* Output */ Enter 2 numbers 10 20 in main function 1st value 20 2nd value 10
Example:2
//by passing reference #include<stdio.h> #include<conio.h> void abc(int &n) { n=100; } int main() { int a=10; printf("a= %d\n",a); abc(a); printf("a= %d\n",a); getch(); return(0); }
/* Output */ a= 10 a= 100
* By using call by reference we can modify any number of values without actually returning any values because in call by reference we make modifications at the very locations where we want to change the values.
* Functions have a limitation that they can return a maximum of one value; this limitation can be overcome by using call by reference.
Question:
Take number calculate and print square and cube.
* Bypassing pointers
* Bypassing reference
* Bypassing pointers
#include<stdio.h> void cal(int n,int *s,int *c) { *s=n*n; *c=n*n*n; } void main() { int a,sq,cu; printf("Enter any no "); scanf("%d",&a); cal(a,&sq,&cu); printf("square = %d cube = %d\n",sq,cu); return(0); }
* Bypassing reference
#include<stdio.h> void cal(int n,int &s,int &c) { s=n*n; c=n*n*n; } int main() { int a,su,cu; printf("Enter any no "); scanf("%d",&a); cal(a,su,cu); printf("square = %d cube = %d\n",su,cu); return(0); }
Question:
Take 2 numbers calculate and print their sum, prod, and diff.
* Bypassing pointers
* Bypassing reference
* Bypassing pointers
#include<stdio.h> void cal(int n1,int n2,int *s,int *p,int *d) { *s=n1+n2; *p=n1*n2; if(n1>n2) *d=n1-n2; else *d=n2-n1; } int main() { int a,b,s,p,d; printf("Enter 2 nos "); scanf("%d %d",&a,&b); cal(a,b,&s,&p,&d); printf("sum = %d prod = %d diff = %d\n",s,p,d); return(0); }
* By passing reference
#include<stdio.h> void cal(int n1,int n2,int &s,int &p,int &d) { s=n1+n2; p=n1*n2; if(n1>n2) d=n1-n2; else d=n2-n1; } int main() { int a,b,s,p,d; printf("Enter 2 nos "); scanf("%d %d",&a,&b); cal(a,b,s,p,d); printf("sum = %d prod = %d diff = %d\n",s,p,d); return(0); }