ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Call by Value and Call by Reference in C Programming Language

Updated on July 7, 2018
rajkishor09 profile image

Raj is an ardent coder who loves exploring new technology. He is an IT pro with 9 years of exp in C#, Angular, React, Vue.

Call by value and call by reference is the most confusing concept among new C language programmer. I also struggled with this, the reason may be my teacher is not explaining it in simple words or I was dumb. Whatever the reason is; here I will try to explain it in simple word. Let’s start with classic example, classic example means whenever people talk about call by value or call by reference, they cite this example i.e. swapping of two variable.

Call by Value and Call by Reference

#include "stdio.h"
#include "conio.h"

void callByValue(int, int);
void callByReference(int *, int *);

int main()
{
	int x=10, y=20;
	clrscr();
	printf("Value of x = %d and y = %d.\n", x,y);

	callByValue(x, y);
	printf("\nCall By Value function call...\n");
	printf("Value of x = %d and y = %d.\n", x,y);

	callByReference(&x, &y);
	printf("\nCall By Reference function call...\n");
	printf("Value of x = %d and y = %d.\n", x,y);

	getch();
	return 0;
}

void callByValue(int x, int y)
{
	int temp;
	temp = x;
	x = y;
	y = temp;
}

void callByReference(int *x, int *y)
{
	int temp;
	temp = *x;
	*x = *y;
	*y = temp;
}
Source

In above call by value and call by reference C program example we have two functions; “callByValue()” and “callByReference()” to demonstrate respective logic.

Let’s start with “callByValue()” function, this function (line no. 25-31) does swapping of variable using temp variable, we have to pass two integer type data as arguments to this function.

The “callByReference()” function (line no. 33-39) also does swapping of variable using temp variable, but we have to pass two integer type pointer as arguments of this function. To reduce confusion; I kept variable name and logic same in both function except some extra asterisk (*) in “callByReference()” function.

We have declared two integer variable in line no. 9. We will pass those two variables to both function and will try to swap value stored in that. First we are calling function “callByValue()” (line no. 13) and we are passing those two integer value. In line no. 15 we are displaying the value of variables (x and y) after swapping. I know that swapping didn’t happen when we called “callByValue()” function.

In line no. 17 we are calling function “callByReference ()” and here we are passing address ofthose two integer variable. In line no. 19 we are displaying the value of variables (x and y). As you can see value of variables (x and y) is successfully swapped.

You must be thinking why this swapping logic worked for “callByReference()” function but not for “callByValue()” function.

Why swapping logic didn’t work for “Call by Value”?

When we called function “callByValue()” in line no. 13 that time we passed value of “x” and “y”, which means we passed copy of “x” and “y” variable value not the actual “x” and “y”. Now you understood why this method of calling function is called “Call by value”? Let me tell you one interesting point about this function, when you will print value of “x” and “y” variable inside this function it will show you the swapped value. But as I told you this logic works on copy of value so those changes will not reflect in “main()” function. See below example and output.

But in case of “callByReference()” function we passed address of “x” and “y” variables (see line no. 17 carefully there we are passing ampersand ‘&’ along with variable name), which means actual location of “x” and “y” variables. So in this function we swapped value which was stored in “x” and “y” location rather than copy of value. As this logic works on address (reference) of variable so this logic is known as “Call by Reference”.

#include "stdio.h"
#include "conio.h"

void callByValue(int, int);
void callByReference(int *, int *);

int main()
{
	int x=10, y=20;
	clrscr();
	printf("Value of x = %d and y = %d.\n", x,y);

	printf("\nCall By Value function call...\n");
	callByValue(x, y);
	printf("Value of x = %d and y = %d.\n", x,y);

	printf("\nCall By Reference function call...\n");
	callByReference(&x, &y);
	printf("Value of x = %d and y = %d.\n", x,y);

	getch();
	return 0;
}

void callByValue(int x, int y)
{
	int temp;
	temp = x;
	x = y;
	y = temp;

	printf("Value of x = %d and y = %d inside callByValue function.\n", x,y);
}

void callByReference(int *x, int *y)
{
	int temp;
	temp = *x;
	*x = *y;
	*y = temp;
}
Source

Your opinion

Did this help you to learn Call by Value and Call by Reference concept?

See results

© 2012 RAJKISHOR SAHU

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Safwan 

      5 months ago

      nice explanation.....

    • profile image

      dipali 

      3 years ago

      thank its really very very helpful

    • profile image

      vickey 

      4 years ago

      thanks sir it's really very helpful

    • profile image

      harshita 

      4 years ago

      Really its very useful to me

    • profile image

      priyanka sharma 

      4 years ago

      thanks

    • profile image

      sunil 

      5 years ago

      really helpfull ......

    • profile image

      kevi 

      5 years ago

      thnks very much

    • profile image

      Ragini 

      5 years ago

      Thanks sir

    • profile image

      Raheel 

      5 years ago

      Thanx sir, it helped a lot

    • profile image

      Pankaj 

      5 years ago

      You are great.......

    • profile image

      aditya.world09@gmail.com 

      6 years ago

      Many Many thnx sir............

    • profile image

      navi 

      6 years ago

      helpful, thanks sir

    • profile image

      sudheer 

      6 years ago

      help something

    • profile image

      sandeep 

      6 years ago

      C made simple

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)