I am not unable to understand the concept used in following code..generally, we
pass address to a function and receive as pointers..but here we r passing values and receiving as addresses..
the code is running successfully. Plz explain concept.
Arguments can be passed to functions by value or by reference. If an argument is passed by value then a copy of its value is created and inside the body of the function the copy of the original argument is processed not the original argument iteslf.
For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
int f( int x )
{
x = 50;
return x;
}
int main()
{
int x = 10;
std::cout << f( x ) << std::endl; // 50 will be outputed
std::cout << x << std::endl; // 10 will be outputed
return 0;
}
Here when function f is called with the argument x a copy of x is created and inside the body of the function the copy of x is assigned 50. The original value of x is not being changed.
Now consider another example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
int f( int &x )
{
x = 50;
return x;
}
int main()
{
int x = 10;
std::cout << f( x ) << std::endl; // 50 will be outputed
std::cout << x << std::endl; // 50 will be outputedreturn 0;
}
In this example the declaration of the function was changed Now its parameter is a reference that is it is declared as int &x. You can consider it as an alias for an argument that will be passed to the function. That is then you call the function and pass it an argument the same argument will be use not its copy. In other words the declaration int &x says use the original value not its copy.