I have the function that returns a nested function:
typedef int (*fp)();
fp makeCounter(){
static int i=0;
fp counter(){
return i++;
}
return counter;
}
int main(){
fp ctr=makeCounter();
printf("%d\n",ctr());
}
makeCounter
returns a function pointer to a locally defined nested function, which to me looks like an undefined behavior.
However I did not find definitive confirmation on this. On the GNU website, it says:
If you try to call the nested function through its address after the containing function exits, all hell breaks loose. If you try to call it after a containing scope level exits, and if it refers to some of the variables that are no longer in scope, you may be lucky, but it’s not wise to take the risk. If, however, the nested function does not refer to anything that has gone out of scope, you should be safe.
I am not very sold on the wording breaks loose
or should be safe
. Is there a definitive confirmation of reference on this topic?
If this is an undefined behavior, is there anyway to get around this? I know usually we define a local variable as static
to allow global access, can we do something similar in this case?
EDIT I understand it is a GNU extension. The question is as above.