什么是复合文字的作为参数传递的寿命? [英] What is the lifetime of compound literals passed as arguments?
问题描述
这编译没有用铿锵的警告。
typedef结构{
INT选项;
int值;
} SOMETYPE;SOMETYPE *的init(SOMETYPE * PTR){
* PTR =(SOMETYPE){
。选项= ptr->选项| ANOTHEROPT,
.value的= 1
}; 返回PTR;
}诠释的main()
{
SOMETYPE * typePtr =的init(及(SOMETYPE){
。选项= SOMEOPT
});
//做别的事情与typePtr
}
-
这甚至合法的C?
-
如果这样:什么是复合的字面寿命
这是在C99或合法的C以上。
C99§6.5.2.5的复合文字的
复合文字的值是由初始化一位不愿透露姓名的对象
初始化列表。如果化合物字面发生功能的身体外,对象
具有静态存储时间;否则,它与相关的自动存储时间
封闭块。
块引用>在你的榜样,文字的化合物具有自动存储,这意味着,它的寿命是其块,即内,在
的main()
函数,它在从@Shafik Yaghmour推荐阅读:
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 }
Is this even valid C?
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:
这篇关于什么是复合文字的作为参数传递的寿命?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!