【问题标题】:Assigning a compound literal to a struct with const fields将复合文字分配给具有 const 字段的结构
【发布时间】:2014-09-28 10:00:43
【问题描述】:

我有以下代码:

test.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 需要一个指向非常量 struct test 的指针,我不确定为什么 GCC 认为我正在尝试修改只读变量。在我看来,我只是将struct test 类型的文字按位分配给(堆栈)变量t,并且结构的字段标记为const 似乎无关紧要。当const 被删除时,GCC 将编译得很好。这是怎么回事?

【问题讨论】:

标签: c c99 compound-literals


【解决方案1】:

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

struct test t;

// from now on, t.i cannot be modified
t.i = 42;  // invalid

【讨论】:

    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 2014-04-03
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    相关资源
    最近更新 更多