ANCI C(C90):可以更改const吗? [英] ANCI C (C90): Can const be changed?

查看:136
本文介绍了ANCI C(C90):可以更改const吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对ANSI规范所说的更改声明为const的变量可以通过其地址合法修改感到困惑.不幸的是,我无法访问C90规范,但指针冲突:

I am confused as to what ANSI specification says about changing a variable declared const can be legally modified through its address. Unfortunately I do not have access to C90 specification but got conflicting pointers:

  1. 关键字const不会将变量变成常量!带有const的符号 限定词仅表示该符号不能用于分配.这使价值 通过该符号重新出现;它不会阻止通过以下方式修改值 程序内部(甚至外部)的其他方式.它仅是非常有用的 用于限定指针参数,以指示此函数将不会更改参数所指向的数据,而其他函数则可以. (专家C编程:深刻的C秘密:彼得·范德·林登)

  1. The keyword const doesn't turn a variable into a constant! A symbol with the const qualifier merely means that the symbol cannot be used for assignment. This makes the value re ad -onl y through that symbol; it does not prevent the value from being modified through some other means internal (or even external) to the program. It is pretty much useful only for qualifying a pointer parameter, to indicate that this function will not change the data that argument points to, but other functions may. (Expert C Programming: Deep C Secrets: Peter van der Linden)

如果尝试通过使用具有非const限定类型的左值来修改以const限定类型定义的对象,则该行为未定义.如果尝试通过使用具有非挥发性限定类型的左值来引用以具有挥发性限定类型定义的对象,则该行为是不确定的. ( http://flash-gordon.me.uk/ansi.c.txt)

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. If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined. (http://flash-gordon.me.uk/ansi.c.txt)

我在C99规范(n1256.pdf)中看到了后者.

I have seen the latter in C99 specification (n1256.pdf).

请问有人可以澄清以上两种观点中的哪一种是正确的吗?

Can anyone clarify as to which of the above two views is true please?

Expect C编程实际上给出了一个示例,以演示使用指针更改const变量的功能.

The Expect C Programming actually gives an example to demonstrate the ability to change a const variable using pointer.

推荐答案

在C90(C89)中与C99类似.

It's similar in C90(C89) as C99.

C89§3.5.3类型限定符

如果尝试通过使用具有非const限定类型的左值来修改以const限定类型定义的对象,则该行为是不确定的.如果尝试通过使用具有非挥发性限定类型的左值来引用以挥发性限定类型定义的对象,则该行为是不确定的.

C89 §3.5.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. If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.

未定义的行为并不意味着C完全禁止它,只是行为是未定义的.因此,实际上您的两个陈述都是正确的.

Undefined behavior doesn't mean that C prohibits it at all, just the behavior is, well, not defined. So actually the two of your statements are both true.

这篇关于ANCI C(C90):可以更改const吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆