Reputation: 25
this code, I want to understand the need to use the reference in the prototype and what will happen if it is not used?
#include<iostream>
using namespace std;
int& fun()
{
static int x = 10;
return x;
}
int main()
{
fun() ;
cout<<fun();
return 0;
}
Upvotes: 0
Views: 55
Reputation: 25623
If you get a reference, you can access the variable from the "outside" world. If you "only" have the value, you can not change the variable anymore.
int& fun()
{
static int x = 10;
return x;
}
int main()
{
std::cout<<fun() << std::endl;
fun()=234;
std::cout<<fun() << std::endl;
return 0;
}
Upvotes: 0
Reputation: 122830
There is no "reference function" here. The &
is part of the return type and should better be written as
int& fun() {...
The function is returning a reference so that you can do
int main()
{
fun() = 6;
cout<<fun(); // will print 6
return 0;
}
If fun
would return an int
not a int&
then the first line would not compile and each call to the function would return you the same value.
Note that in most cases returning a reference to a function local variable is wrong. The reason it is fine here is that x
is static
, meaning: it will be initialized exactly once and keeps its value across function calls.
For example this function will return a counter of how many times it got called:
int count_me() {
static int x = 0;
x+=1;
return x;
}
Upvotes: 1