Announcement:

This is just the beginning of this blog, please don't copy any of my posts.

Friday, 6 September 2013

Simple Example with Explanation For Call By Reference Function in C Programming [With Output]

If data is passed by reference, a pointer to the data is copied instead of the actual variable as is done in a call by value. Because a pointer is copied, if the value at that pointers address is changed in the function, the value is also changed in main(). Let’s take a look at a code example:
Program

#include<stdio.h>
#include<conio.h>
void main()
{
int x,y;
void swap(int *,int *);
clrscr();
puts("Enter the values of x & y \n");
scanf("%d%d",&x,&y);
swap(&x,&y);
printf("X=%d \ny=%d",x,y);
getch();
}
void swap(int *a,int *b)
{
int z;
z=*a;
*a=*b;
*b=z;
}

The output of this call by reference source code example will look like this:

Output:

Enter The value of x and y
2
4
X=4
Y=2

Let’s explain what is happening in this source code example. We start with an integer b that has the value 10. The function call_by_reference() is called and the address of the variable b is passed to this function. Inside the function there is some before and after print statement done and there is 10 added to the value at the memory pointed by y. Therefore at the end of the function the value is 20. Then in main() we again print the variable b and as you can see the value is changed (as expected) to 20.
Share it Please

Pankaj Gaikar

Pankaj Gaikar is a professional blogger from Pune, India who writes on Technology, Android, Gadgets, social media and latest tech updates at Punk Tech , Being Android & Shake The Tech . Email me HERE

0 comments :

Post a Comment

Copyright @ 2013 Pune University Bachelor of Engineering . Designed by Pankaj Gaikar | Love for The Tricks Machine