#include <iostream>
using namespace std;
bool a[5];
int main()
{
for (int i = 0; i < 5; i++)
{
cout<<a[i]<<" ";
}
return 0;
}
以上代码中输出为0 0 0 0 0
,但是下面代码输出却是不确定的.这是为什么?
#include <iostream>
using namespace std;
int main()
{
bool a[5];
for (int i = 0; i < 5; i++)
{
cout<<a[i]<<" ";
}
return 0;
}
输出176 74 183 230 255
A in both pieces of code is initialized by default. The difference is that the global variable a will first be zero-initialized (zero-initialized) before the default initialization, while the local variable a will not (this does not mean that the local variable will not be initialized to 0). At the same time, the value of this default-initialized local variable a is uncertain. So the value of global variable a here is 0, and the value of local variable a is uncertain.
Whether a variable will actually be initialized to 0 is related to the storage duration of the variable. Static variables are initialized to 0 before initialization, while automatic variables are not.
Because undefined global variables will be initialized to 0, but local variables declared within functions do not have this rule
Generally speaking, global variables and static variables are placed in the data segment, while local variables are placed in the stack.
The data segment is determined during compilation and allocated in the executable file, so it will definitely be initialized.
As for the stack, we know that it is allocated at runtime. When entering a function, in addition to registers being pushed onto the stack, stack space is also allocated to temporary variables, so local variables correspond to a stack address. The stack changes greatly in memory, so the initial value is uncertain.
Of course, the C++ standard does not specify which area the compiler should place variables in, but this is generally how it is implemented.