c - 通过 const 左值访问非常量对象是否安全?

标签 c constants language-lawyer

6.5(p7) 指出:

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:88)

— a type compatible the effective type of the object,

— a qualified version of a type compatible with the effective type of the object,

— a type that is the signed or unsigned type corresponding to the effective type of the object,

— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,

看看 6.7.3(p10):

For two qualified types to be compatible, both shall have the identically qualified version of a compatible type;

所以 doubleconst double 不兼容,因为它们的类型限定符不一样。

现在我假设signed or unsigned type 是指 signed or unsigned integer type as defined it 6.2.5(p4)6.2.5(p6) 相应地,因为 6.2.5 本身没有定义签名类型

现在考虑以下代码:

void print_double(const double d){
    printf("d = %lf\n", d);
}

int main(int args, const char *argv[]){
    double d = 10.2;
    print_double(d);
}

现在我尝试应用 6.5 (p7):

我。 与对象的有效类型兼容的类型

不,const doubledouble 不兼容。

二。 与对象的有效类型兼容的类型的合格版本

不,const double 的合格版本会比 const double 更合格

三/四。

不,double 不是有符号或无符号整数类型。

这个判断似乎是错误的,因为通过 const 限定的左值访问非常量对象应该是可以的。但我无法从 6.5(p7) 中得出它。

最佳答案

Now consider the following code:

void print_double(const double d){
    printf("d = %lf\n", d);
}

int main(int args, const char *argv[]){
    double d = 10.2;
    print_double(d);
}

您的代码不做任何别名。 main 中的 dprint_double 中的 ddistinct 对象,因为参数总是按值传递。但是如果我们要“修复”这个例子:

void print_double(const double *pd){
    printf("d = %lf\n", *pd);
}

int main(int args, const char *argv[]){
    double d = 10.2;
    print_double(&d);
}

它仍然定义明确。 *pdconst double 类型的左值。 const doubledouble 的合格版本。所有类型都与自身兼容(平凡)。所以第二个项目符号成立,这个别名是有效的。

关于c - 通过 const 左值访问非常量对象是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55236473/

相关文章:

c - 使用C打印服务器IP地址

C++/CLI 内存编码/别名和结构互操作性

c - 多线程 Windows 回调函数

css - 在CSS Flexbox中,为什么没有“justify-items”和“justify-self”属性?

c - 数组外指针比较的基本原理是 UB

无法从 "gets()"输入

C# const 与 lambda 效率

sql - 如何选择充满常量的多行?

c++ - 确保const指针成员变量的constness

c - 如何使用 `offsetof` 以符合标准的方式访问字段?