10

これは、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ですか?

  2. もしそうなら: 複合リテラルの寿命は?

4

2 に答える 2

10

C99以降の有効なCです。

C99 §6.5.2.5複合リテラル

複合リテラルの値は、初期化子リストによって初期化された名前のないオブジェクトの値です。複合リテラルが関数の本体の外側にある場合、オブジェクトには静的な保存期間があります。それ以外の場合は、囲んでいるブロックに関連付けられた自動保存期間があります。

あなたの例では、複合リテラルには自動ストレージがあります。つまり、その寿命はそのブロック内、つまりmain()それが含まれる関数内にあります。

@Shafik Yaghmour からの推奨読書:

  1. 新しい C: 複合リテラル
  2. GCC マニュアル: 6.25 複合リテラル
于 2014-02-19T13:57:13.327 に答える
4

Yu Hao は標準で回答しましたが、現在は下品になっています。

次のような複合リテラルが表示されるたびに:

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

次のように置き換えることができます。

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

そう:

main.c

#include <assert.h>

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

int f(struct S *s) {
    return s->i + 1;
}

int main() {
    /* Undefined behaviour: not defined yet.
     * GCC 10 -fsanitize=undefined -ggdb3 -O0 -std=c99 gives at runtime:
     * runtime error: member access within null pointer of type 'struct S' */
#if 0
    assert(f(s2) == 1);
#endif

    /* Lives inside main, and any function called from main. */
    s2 = &(struct S){1};
    /* Fine because now instantiated. */
    assert(f(s2) == 2);

    /* Only lives in this block. */
    {
        s3 = &(struct S){1};
        /* Fine. */
        assert(f(s3) == 2);
    }
    {
        /* On GCC 10 -O0, this replaces s3 above due to UB */
        s4 = &(struct S){2};
    }
    /* Undefined Behavior: lifetime has ended in previous block.
     * On GCC 10, ubsan does not notice it, and the assert fails
     * due to the s4 overwrite.*/
#if 0
    assert(s3->i == 1);
#endif
}

完全なコンパイル コマンド:

gcc -fsanitize=undefined -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
于 2015-07-02T08:08:22.003 に答える