1

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Jayesh
  • 4,755
  • 9
  • 32
  • 62
  • 3
    well-defined. In this case it is not necessary to be `static`. Its same as `return 10;` – BLUEPIXY Nov 03 '17 at 10:05
  • perfectly well defined.. – Srikanth Chekuri Nov 03 '17 at 10:06
  • Maybe I rushed my answer, just to clarify, is there anything in specific that makes you think this would be UB? – Sourav Ghosh Nov 03 '17 at 10:36
  • 4
    I believe you are confusing this with `int* fun (void) { static int i = 10; return &i; }` versus `int* fun (void) { int i = 10; return &i; }`, which is another story. The former is well-defined, the latter is undefined behavior. – Lundin Nov 03 '17 at 10:53

1 Answers1

8

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.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261