什么是复合文字的作为参数传递的寿命? [英] What is the lifetime of compound literals passed as arguments?

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

问题描述

这编译没有用铿锵的警告。

  typedef结构{
  INT选项;
  int值;
} SOMETYPE;SOMETYPE *的init(SOMETYPE * PTR){
  * PTR =(SOMETYPE){
    。选项= ptr->选项| ANOTHEROPT,
    .value的= 1
  };  返回PTR;
}诠释的main()
{
  SOMETYPE * typePtr =的init(及(SOMETYPE){
    。选项= SOMEOPT
  });
  //做别的事情与typePtr
}


  1. 这甚至合法的C?


  2. 如果这样:什么是复合的字面寿命



解决方案

这是在C99或合法的C以上。


  

C99§6.5.2.5的复合文字


  
  

复合文字的值是由初始化一位不愿透露姓名的对象
  初始化列表。如果化合物字面发生功能的身体外,对象
  具有静态存储时间;否则,它与相关的自动存储时间
  封闭块。


在你的榜样,文字的化合物具有自动存储,这意味着,它的寿命是其块,即内,在的main()函数,它在

从@Shafik Yaghmour推荐阅读:


  1. 新C:复合文字

  2. GCC手册:6.25复合文字

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. Is this even valid C?

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

解决方案

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.

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.

Recommended reading from @Shafik Yaghmour:

  1. The New C: Compound Literals
  2. GCC Manual: 6.25 Compound Literals

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

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