#include <stdio.h>
int main(void) {
const int a = 4;
int *p = (int*)&a;
printf("%d\n", a);
*p = 6;
printf("%d\n", a);
return 0;
}
代码在 C 和 C++ 编译器上给出不同的输出:
//In C:
4
6
//In C++:
4
4
尝试修改
const
值(只读值)是未定义行为。输出可以是任何内容,否则程序可能会崩溃,或者将你的狗推入太空。你已被警告过。
关于
const
、常量和只读值
const
是一个错误选择的关键字,因为它并不意味着“常量”,而是“只读”。 “constants”是只读 values 的名称,仅此而已。 “只读”(此处)的反义词是“读写”,“常量”的反义词是“可变”。 Mutable 是 C 和 C++ 中的默认值(除了一些罕见的极端情况,例如 lambda)。考虑一下:
int i = 4; // (mutable) Value
int const j = 4; // Read-only value, a.k.a constant
// Pointer to a (mutable) value. You can write to the value through it.
int *pi = &i;
// Pointer giving read-only access to a value. The value
// is still mutable, but you can't modify it through cpi.
int const *cpi = &i;
// Since the value is mutable, you can do that and write to *p2i
// without trouble (it's still bad style).
int *p2i = (int*)cpi;
// Pointer giving read-only access to a value.
// The value is a constant, but you don't care
// since you can't modify it through cpj anyway.
int const *cpj = &j;
// This is legal so far, but modify *pj
// (i.e the constant j) and you're in trouble.
int *pj = (int*)cpj;
什么时候可以这样做?
允许您强制转换
const
的唯一情况是将指针(或引用)传递给您无法修改的错误声明的函数(或类似函数):
// Takes a non-const pointer by error,
// but never modifies the pointee for sure
int doSomething(Foo *foo);
// Your function, declared the right way
// as not modifying the pointee
int callDoSomething(Foo const *foo) {
// Work around the declaration error.
// If doSomething ever actually modifies its parameter,
// that's undefined behaviour for you.
int bar = doSomething((Foo*)foo);
}
怎样做才能不被咬?
这在 C 和 C++ 中都是未定义的行为。
A
const
变量不应被修改,这包括直接修改它,还包括间接修改它(通过像您的示例中那样的指针)。
虽然其他答案已经涵盖了这是未定义的行为,但这里的转换:
int* p = (int*)&a;
不好。它隐藏了您应该收到的警告:
main.cpp:6:10: warning: initialization discards 'const' qualifier from pointer target type
int* p = &a;