What is the lifetime of compound literals passed as arguments?

折月煮酒 提交于 2019-11-28 13:34:11

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

Yu Hao has answered with the standard, now some vulgarization.

Whenever you see a compound literal like:

struct S *s;
s = &(struct S){1};

you can replace it with:

struct S *s;
struct S __HIDDEN_NAME__ = {1};
s = &__HIDDEN_NAME__;

So:

struct S {int i;};
/* static: lives for the entire program. */
struct S *s = &(struct S){1};

int main() {
   /* Lives inside main, and any function called from main. */
   s = &(struct S){1};

   /* Only lives in this block. */
   {
       s = &(struct S){1};
   }
   /* Undefined Behavior: lifetime has ended. */
   s->i;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!