Returning local static in C

妖精的绣舞 提交于 2020-01-03 02:37:09

问题


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?


回答1:


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.


来源:https://stackoverflow.com/questions/47093032/returning-local-static-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!