c++ - 未命名命名空间中的变量自动初始化为 0?

标签 c++ namespaces initialization

我的理解是,静态变量被放入二进制文件的未初始化变量部分(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/

相关文章:

c++ - con.txt 和 C++

c++ - 带有枚举的 'using' 声明

c++ - C++ 中的循环包含 - 再次

c++ - 引用表亲命名空间

ruby-on-rails - 获取 rails Controller 对象的命名空间?

perl - 用于测量 Text::Document 中 CosineSimilarity 的变量未初始化

我可以声明一个数组并只为其第一个元素分配一个初始值吗?

java - war 级别初始化, "main"为 war

c++ - OpenMP #pragma omp for v/s #pragma omp parallel for之间的区别?

php - 如何对php类进行分组?