2
我有以下代码:分配文字与常量字段的结构的化合物
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
需要一个指向非const的指针struct test
我不确定为什么GCC认为我试图修改一个只读变量。在我看来,我只是将类型为struct test
的文字按位分配给(堆栈)变量t
,并且结构的字段标记为const
似乎并不重要。当const
被删除时,GCC将会正常编译。这里发生了什么?
'clang'中的错误? – alk 2014-09-28 10:29:21
也许相关:http://stackoverflow.com/questions/3531296/have-i-found-a-bug-in-clang – mafso 2014-09-28 10:38:50
void foo(struct bar {const int n;} b1,struct bar b2){b1 = b2; }'也重现了这个问题(clang给出了一个结构定义的警告,只有在这个函数中才可见,这很好,但在这里不相关)。 – mafso 2014-09-28 10:52:04