In C language, scope of the static
variable through out the file.
In the following code, function returns the static variable.
int fun(){
static int i = 10;
return i;
}
int main() {
printf("%d\n", fun());
return 0;
}
And printed output 10.
So, Is returning local static in C undefined behaviour or well-defined?
You seem to have missed the whole logic for a return
statement.
In this snippet, you are actually returning the value (of the variable), so, without the static
storage also, the code is fine.
In case, you want to return the address of a variable, it needs to outlast the scope of the function. In that case, you need to have a variable with static
storage, so that the returned address is valid (so that it can be used meaningfully from the caller function) even outside the function in which it is defined. So, either
- you use a pointer returned by allocator functions, like
malloc()
or family
- use the address of a variable defined with
static
storage class.