C和C++中未定义,未指定和实现定义的行为有什么区别?
c c++ undefined-behavior unspecified-behavior implementation-defined-behavior
我在下面的代码片段中找到了
const int i = 2;
const int* ptr1= &i;
int* ptr2 = (int*)ptr1;
*ptr2 =3;
Run Code Online (Sandbox Code Playgroud)
i价值变为3.我想知道的是为什么允许这样做.有什么情况可以变得有用?
可能重复:
通过非const指针修改const
我正在学习C++,对指针非常有趣.而我试图改变一个恒定值的值(我的老师叫它backdoor,请澄清我是不是错了)像这样:
const int i = 0;
const int* pi = &i;
int hackingAddress = (int)pi;
int *hackingPointer = (int*)pi;
*hackingPointer = 1;
cout << "Address:\t" << &i << "\t" << hackingPointer << endl;
cout << "Value: \t" << i << "\t\t" << *hackingPointer << endl;
system("PAUSE");
return 0;
Run Code Online (Sandbox Code Playgroud)
但是,结果很奇怪.虽然两个地址相同,但值不同.

我的代码是如何执行的?哪里0和1价值准确存储?
可能重复:
通过非const指针修改const
我有以下代码:
const int x = 5;
int *p = (int*)&x;
*p = 2; // Line 1
cout << x << " - " << *p << endl;
cout << &x << " - " << p << endl;
Run Code Online (Sandbox Code Playgroud)
并得到了结果:
5 - 2
0012FF28 - 0012FF28
Run Code Online (Sandbox Code Playgroud)
我知道代码很奇怪,不应该这样做.但我想知道为什么相同的地址但得到不同的结果?哪个Line 1商店2号?
场景1:当const变量在内部声明时main(),即变为局部变量
#include <stdio.h>
#include <conio.h>
main()
{
const int a = 45;
* ((int*)&a)=50;
printf("%d\n",a);
getch();
}
Run Code Online (Sandbox Code Playgroud)
输出MVC++:
一个= 50
场景2:当const变量在外部声明时main(),即变为全局变量
#include <stdio.h>
#include <conio.h>
const int a = 45;
main()
{
* ((int*)&a)=50;
printf("%d\n",a);
getch();
}
Run Code Online (Sandbox Code Playgroud)
输出MVC++:
未处理的异常......违规行为.
我理解为什么在尝试修改全局定义的const变量时会出现错误.但是,当我尝试修改const本地定义的变量时,为什么我没有收到错误?