06-01-2011, 10:47 PM
Call by value : its means when we call a function and pass some argument to it we are passing the copy of the argument instead of original variable
Call by value:
1
2
3
4
5
6
7
void foo( int x ) {
cout << x << endl;
x = 4;
}
int someVar = 5;
foo( someVar );
The value 5 is pushed onto the stack and foo is called. Inside foo(), 5 is popped off the stack and output. x = 4 modifies the stack copy, which is then thrown away when the function returns.
1
2
3
4
5
6
7
void foo( int& x ) {
cout << x << endl;
x = 4;
}
int someVar = 5;
foo( someVar );
The address of someVar is pushed onto the stack and foo is called. Inside foo, the address is popped off the stack and the integer stored at that address is output. x = 4 modifies the memory referred to by the address, which means that when foo() returns, someVar now has the value 4.
Contrast the above code to
1
2
3
4
5
6
7
void foo( int* x ) {
cout << *x << endl;
*x = 4;
}
int someVar = 5;
foo( &someVar );
0300-9520262
Get solution in 24 hour |cpmputer & internet
mileys81:[SIZE="4"][SIZE="3"]....[/SIZE][/SIZE]
