这样做可以吗?
struct MyStruct {
int x;
const char y; // notice the const
unsigned short z;
};
struct MyStruct AStruct;
fread(&MyStruct, sizeof (MyStruct), 1,
SomeFileThatWasDefinedEarlierButIsntIncludedInThisCodeSnippet);
我通过从文件写入整个结构来更改常量结构成员。那应该如何处理呢?如果一个或多个结构成员是常量,则写入非常量结构是否是未定义的行为?如果是这样,处理常量结构成员的公认做法是什么?
最佳答案
这是未定义的行为。
C11 草案 n1570 说:
6.7.3 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 成员的值,例如:
struct MyStruct AStruct = {1, 'a', 2}; // Fine
正在做
AStruct.y = 'b'; // Error
应该给出编译器错误。
您可以使用如下代码欺骗编译器:
memcpy(&AStruct, &AnotherStruct, sizeof AStruct);
它可能在大多数系统上都能正常工作,但根据 C11 标准,它仍然是未定义的行为。
关于c - C 中如何处理常量结构成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62464232/