Let's walk through your program step by step:
- inside
main()
fun()
is called.
fun()
has a static variable x
(static means, that x
is stored in a special part of memory and not on the stack, so its value is preserved between function calls) (It's like having a global variable that is only visible from inside fun()
)
fun()
returns a reference to x
(references are almost like pointers)
- You write to the returned reference of
x
, so x
actually gets changed! (You don't write to the function)
- now
x
is 30 and fun()
returns 30 on the next call.
I hope this answers your first three questions.
Why you get a segmentation fault without the static keyword:
In this case x
does exist on the stack. So whenever you call fun()
some memory gets allocated on the stack to hold x
. When fun()
returns, this memory will be deallocated.
Now, the reference returned by fun()
, will reference a piece memory, that is not allocated by your program anymore. In other words, the returned reference will reference a memory address, that does "not belong to your program", thus you are not allowed to write to it. And so you get a segmentation fault.
Can we assign values to function:
To answer the actual title of your question: Yes, we can, using function pointers:
int foo(int x) {
return x + 1;
}
int bar(int x) {
return x * 2;
}
void main() {
int(*f)(int) = foo;
// int the function pointed to returns an int
// (*f) f is the name of the function pointer
// (int) the function pointed to takes on int as paramter
// = foo; f now points to the function foo()
(*f)(3); // the same as foo(3), returns 4
f = bar; // now f points to bar()
(*f)(3); // the same as bar(3), returns 6
}