Posted By:
3 Jul, 2013 12:57 pm PDT

Call by value in C++

Call by value is used in functions. But what is call by value?
Attachment:None


Call by value means when calling a function with parameters, what we passed to the function were copies of their values but never the variable themselves.

For example:

//swapping of two numbers

#include<iostream.h>

void swap(int a, int b)

{

int temp;

temp=a;

a=b;

b=temp;

cout<<”\nIn function:

cout<<a<<”\t”<<b;

}

void main()

{

int x,y;

x=5;y=3;

swap(x,y);

cout<<”\nIn main”;

cout<<x<<”\t”<<y;

}

 

Output of the above code is:

In function: 3   5

In main:5     3

 

Explanation:

In the main() the value of x and y are not changed even though they are passed to swap() because the value of x and y is just copied to the local variables a and b. Hence changes made to ‘a’ and ‘b’ does not have any effect on ‘a’ and ‘b’.

Was it useful?  




Please login to reply to this problem.