作为参数传递的复合文字的生命周期是多少? [英] What is the lifetime of compound literals passed as arguments?

查看:23
本文介绍了作为参数传递的复合文字的生命周期是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 clang 编译时没有警告.

This compiles without warnings using clang.

typedef struct {
  int option;
  int value;
} someType;

someType *init(someType *ptr) {
  *ptr = (someType) {
    .option = ptr->option | ANOTHEROPT,
    .value = 1
  };

  return ptr;
}

int main()
{
  someType *typePtr = init( &(someType) {
    .option = SOMEOPT
  });
  // do something else with typePtr
}

  1. 这甚至是有效的 C 吗?

  1. Is this even valid C?

如果是:复合文字的生命周期是多少?

If so: What is the lifetime of the compound literal?

推荐答案

它在 C99 或更高版本中有效.

It's valid C in C99 or above.

复合字面量的值是由初始化列表.如果复合字面量出现在函数体之外,则对象具有静态存储期限;否则,它具有与关联的自动存储持续时间封闭块.

C99 §6.5.2.5 Compound literals

The value of the compound literal is that of an unnamed object initialized by the initializer list. If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

在您的示例中,复合文字具有自动存储功能,这意味着它的生命周期在其块内,即它所在的 main() 函数.

In your example, the compound literal has automatic storage, which means, its lifetime is within its block, i.e, the main() function that it's in.

@Shafik Yaghmour 的推荐阅读:

Recommended reading from @Shafik Yaghmour:

  1. 新的 C:复合字面量
  2. GCC 手册:6.25 复合字面量

这篇关于作为参数传递的复合文字的生命周期是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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