C语言const研究
刚刚写了一段这样子的代码:
#include <stdio.h> int main() { const int two = 2; int *one = &two; *one =1; printf("%d\n", two); return 0; }
在ANSI C中运行通过了。 结果发现竟然成功输出了=。=、 看来C语言的常量限制仅陷于某个变量名啊。
1
在K & R C中则不能通过,因为不相容问题。
C++也是不行的:
#include <iostream> using namespace std; int main() { const int two = 2; int *one = const_cast<int *>(&two); *one = 1; printf("%p %p\n", one, &two); printf("%d\n", two); printf("%d\n", *one); return 0; }
运行结果:
0x7fff65150a54 0x7fff65150a54 2 1
诡异地出现同样地址不一样的值!
进一步修改代码:
#include <iostream> using namespace std; int main() { const int two = 2; int *one = const_cast<int *>(&two); printf("%d\n", *one); *one = 1; printf("%p %p\n", one, &two); printf("%d\n", two); printf("%d\n", *one); int *three = const_cast<int *>(&two); printf("%d\n", *three); return 0; }
结果:
2 0x7fff669b6a54 0x7fff669b6a54 2 1 1
有一种常量和变量完全剥离的感觉! 于是在stackoverflow上发现下面这段子:
In C++ language it is illegal to attempt to modify constant objects. Such an attempt results in undefined behavior. In your program the *p = 2 assignment attempts to modify a constant object a. The behavior is undefined. The weird output you observe is exactly that: undefined behavior. There's no meaningful explanation for undefined behavior. (Your compiler probably translated the cout << a; statement into cout << 1;, since the value of a cannot legally change. So, regardless of what you do to your a, 1 will always be printed.)