What is the lifetime of compound literals passed as arguments?

后端 未结 2 1614
慢半拍i
慢半拍i 2020-12-11 16:33

This compiles without warnings using clang.

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

someType *init(someType *ptr) {
  *ptr = (someType) {
           


        
2条回答
  •  星月不相逢
    2020-12-11 17:01

    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;
    }
    

提交回复
热议问题