【问题标题】:Returning local static in C在 C 中返回本地静态
【发布时间】:2017-11-03 10:04:35
【问题描述】:

在 C 语言中,static 变量的作用域贯穿整个文件。 在以下代码中,函数返回静态变量。

int fun(){
    static int i = 10;
    return i;
}

int main() {
    printf("%d\n", fun());
    return 0;
}

并打印输出 10。

那么,在 C 中返回 local static 是未定义的行为还是明确定义的?

【问题讨论】:

  • 定义明确。在这种情况下,不必是static。与return 10; 相同
  • 定义完美..
  • 也许我匆忙回答,只是为了澄清一下,有没有什么具体的东西让你认为这会是 UB?
  • 我相信您将此与 int* fun (void) { static int i = 10; return &i; }int* fun (void) { int i = 10; return &i; } 混淆了,这是另一个故事。前者是明确定义的,后者是未定义的行为。

标签: c variables static return return-value


【解决方案1】:

您似乎错过了return 声明的整个逻辑

在这个 sn-p 中,您实际上是在返回 (变量的),因此,如果没有 static 存储,代码也可以。

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

  • 您使用分配器函数返回的指针,例如 malloc() 或 family
  • 使用static存储类定义的变量地址。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 2015-08-17
    • 2014-07-02
    • 1970-01-01
    相关资源
    最近更新 更多