<分区>
#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
<分区>
#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
是一个错误的关键字,因为它并不意味着“常量”,而是“只读”。 “常量”是赋予只读值 的名称,仅此而已。 “只读”(此处)的反义词是“读写”,“常量”的反义词是“可变”。可变是 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 和 C++ 中 const 变量的不同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25425941/