Functions and pointers

#include
using namespace std;

int &fun()
{
static int x = 10;
return x;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
how we can use &operator with a function? nd how this code is working?

hi @tishya_goyal please save your code on ide.codingblocks.com and share the link.

@tishya_goyal may I know the source of this code? Or the context at least? I have never seen such syntax myself.
Dereference operator is often used with function arguments to pass them by reference instead of passing them by value.

i saw it in geek for geeks

@tishya_goyal share the link of that article

hi @tishya_goyal when we return a value by reference, its address is passed instead of the value itself. So one important thing to keep in mind is that the scope of that value should not end when that function is over. So it can either be a static member (like in this example) or it can be a global variable.
our return type is int & so when we return x, address of x is returned, and then it is assigned the value “30” in the main function.

ok ok
now i got it
thank u so much!!!

1 Like

@tishya_goyal please mark the doubt as resolved :slight_smile:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

int &fun()
{
static int x = 10;
return x;
}

and

int &fun()
{
int x = 10;
return x;
}

bhai please help why 2nd nt working