2

我有以下代码:

测试.c

struct test {
    int const i;
};

void init_test(struct test *t)
{
    *t = (struct test){42};
}

int main(int argc, char **argv)
{
    (void)argc; (void)argv;

    struct test t;
    init_test(&t);
    /* I would expect t={42} here */
}

编译gcc -std=c99 -Wall test.c -o test失败并出现以下错误:

error: assignment of read-only location '*t"
    *t = (struct test){42}
     ^

而编译clang -std=c99 -Wall test.c -o test成功并且生成的可执行文件的行为符合预期。首先,我的示例代码格式正确吗?由于该函数init_test需要一个指向非 const 的指针,struct test我不确定为什么 GCC 认为我正在尝试修改只读变量。在我看来,我只是将类型的文字按位分配给struct test(堆栈)变量t,并且标记结构的字段似乎无关紧要constconstGCC 将在删除时编译正常。这里发生了什么?

4

1 回答 1

2

它不是复合文字所特有的。结构const成员只能被初始化,一旦对象被定义就不能被修改。

struct test t;

// from now on, t.i cannot be modified
t.i = 42;  // invalid
于 2014-09-28T10:13:03.673 回答