我可以写入非常量结构的 const 成员吗?

标签 c language-lawyer standards

这段代码合法吗?:

#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);

}

最佳答案

修改使用 const 限定符声明的对象会调用 undefined behavior .

根据标准(强调我的):

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 成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42056823/

相关文章:

计数器值在 while 循环内的 if else 条件下仅递增一次

c - 将数据格式化为十六进制字符串以增加 C 中的 MD5 哈希计算

c++ - 条件运算符 + upcast + const 引用

c++ - 补码架构上的负零行为?

C中使用递归计算数组的累加和

c - xCode 产生 "Undefined symbols for architecture x86_64"错误,而 gcc 编译没有错误

c++ - "typedef"在类型和别名标准符合之间吗?

c++ - Mozilla C/C++ 编码风格

c++ - C++标准中未定义行为段落中的[Note]是什么意思?

c++ - 与 const 和非常量相同的对象,我应该假设什么才能正确运行?