在 C 中返回本地静态 [英] Returning local static in C

查看:52
本文介绍了在 C 中返回本地静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C 语言中,整个文件中 static 变量的范围.在下面的代码中,函数返回静态变量.

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;
}

并打印输出 10.

那么,在 C 未定义行为中返回 local static 还是定义良好?

So, Is returning local static in C undefined behaviour or well-defined?

推荐答案

您似乎错过了 return 语句的整个逻辑.

You seem to have missed the whole logic for a return statement.

在此代码段中,您实际上返回了(变量的),因此,如果没有 static 存储,代码也可以.

In this snippet, you are actually returning the value (of the variable), so, without the static storage also, the code is fine.

如果你想返回一个变量的地址,它需要超过函数的作用域.在这种情况下,您需要有一个带有 static 存储的变量,这样即使在定义它的函数之外,返回的地址也是有效的(以便可以从调用者函数中有意义地使用它).所以,要么

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

  • 您使用分配器函数返回的指针,例如 malloc() 或 family
  • 使用由 static 存储类定义的变量的地址.
  • you use a pointer returned by allocator functions, like malloc() or family
  • use the address of a variable defined with static storage class.

这篇关于在 C 中返回本地静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆