gpt4 book ai didi

c++ - 未初始化变量的值是如何确定的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:00:06 27 4
gpt4 key购买 nike

给定一个程序:

int main()
{

short myVariableName1; // stores from -32768 to +32767
short int myVariableName2; // stores from -32768 to +32767
signed short myVariableName3; // stores from -32768 to +32767
signed short int myVariableName4; // stores from -32768 to +32767
unsigned short myVariableName5; // stores from 0 to +65535
unsigned short int myVariableName6; // stores from 0 to +65535

int myVariableName7; // stores from -32768 to +32767
signed int myVariableName8; // stores from -32768 to +32767
unsigned int myVariableName9; // stores from 0 to +65535

long myVariableName10; // stores from -2147483648 to +2147483647
long int myVariableName11; // stores from -2147483648 to +2147483647
signed long myVariableName12; // stores from -2147483648 to +2147483647
signed long int myVariableName13; // stores from -2147483648 to +2147483647
unsigned long myVariableName14; // stores from 0 to +4294967295
unsigned long int myVariableName15; // stores from 0 to +4294967295
cout << "Hello World!" << endl;
cout << myVariableName1 << endl;
cout << myVariableName2 << endl;
cout << myVariableName3 << endl;
cout << myVariableName4 << endl;
cout << myVariableName5 << endl;
cout << myVariableName6 << endl;
cout << myVariableName7 << endl;
cout << myVariableName8 << endl;
cout << myVariableName9 << endl;
cout << myVariableName10 << endl;
cout << myVariableName11 << endl;
cout << myVariableName12 << endl;
cout << myVariableName13 << endl;
cout << myVariableName14 << endl;
cout << myVariableName15 << endl;
cin.get();

return 0;
}

打印出未分配的变量将打印之前存储在该内存位置的任何内容。我注意到,在多次连续执行中,打印的值没有改变 - 这告诉我每次执行时内存中的位置都是相同的。

我只是好奇这是怎么确定的,为什么会这样。

最佳答案

这些变量存在于堆栈中。程序的执行看起来是确定性的,所以每次运行它时都会发生同样的事情。它不一定选择相同的地址(如今许多运行时都使用地址空间随机化技术来确保堆栈地址在运行之间相同),但堆栈上的相对地址包含相同的地址每次都有数据。

关于c++ - 未初始化变量的值是如何确定的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12863777/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com