我可以写入非const结构的const成员吗? [英] Can I write to a const member of a non-const struct?
本文介绍了我可以写入非const结构的const成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码合法吗?:
#include <stdio.h>
typedef struct a_d{
int const x;
} a_d;
int a_d__ctor(a_d *X)
{
*(int*)&X->x = 42; //<-- legal or not?
return 0;
}
int main()
{
a_d a;
a_d__ctor(&a);
printf("a.x=%d\n", a.x);
}
推荐答案
Modyfing an object declared with const
qualifier invokes undefined behavior.
根据标准(强调我):
C11 6.7.3/6 类型限定符
如果尝试修改用 通过将左值与非const限定符结合使用来实现const限定符类型 类型,则行为是不确定的.
C11 6.7.3/6 Type qualifiers
If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.
这篇关于我可以写入非const结构的const成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文