我的理解是,静态变量被放入二进制文件的未初始化变量部分(BSS 部分),因此可以安全地假设这些变量被初始化为 0。
但是我在未命名的命名空间中定义了一个函数。函数内部声明了一个char数组,没有显式初始化为0,这个会自动初始化为0吗?未声明为静态但在未命名命名空间中定义的变量怎么办?那么静态函数的局部变量呢?
最佳答案
函数局部变量不会自动初始化为零,无论该函数是在匿名命名空间、静态还是其他任何地方。这是因为函数内部的局部变量不是静态变量。要使局部变量具有静态存储持续时间,您必须用 static
显式标记它。
int foo; // static storage duration (because it's global) automatically zero-initialized
static int foo2; // static storage duration (because it's global) automatically zero-initialized. The static keyword just gives the name 'foo2' internal linkage and has nothing to do with static storage duration.
namespace {
int foo; // static storage duration, automatically zero-initialized
void bar() {
int f; // local variable, not automatically zero-initialized
static int g; // static storage duration (because of the keyword static), automatically zero-initialized
}
}
关于c++ - 未命名命名空间中的变量自动初始化为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6526466/