本文介绍了未命名的命名空间中自动初始化为0的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是静态变量放在二进制文件的未初始化变量部分(BSS部分),因此可以安全地假设为初始化为0。

My understanding is that static variables get put in the uninitialized variable section of the binary (the BSS section) and so those are safe to assume as being initialized to 0.

但我有一个在未命名的命名空间中定义的函数。在函数内部,有一个字符数组声明没有显式初始化为0.这将自动初始化为0?关于未声明为静态但在未命名的命名空间中定义的变量怎么办?关于静态函数的局部变量呢?

But I have a function defined in an unnamed namespace. Inside the function, there is a char array declared without being explicitly initialized to 0. Will this be auto-initialized to 0? What about variables not declared as static but defined in an unnamed namespace? And what about local variables of static functions?

推荐答案

函数局部变量不会自动初始化为零,函数是在匿名命名空间,静态,或任何。这是因为函数内部的局部变量不是静态变量。要使局部变量具有静态存储持续时间,必须使用 static 明确标记。

A function local variable will not be automatically initialized to zero, regardless of whether the function is in an anonymous namespace, static, or whatever. This is because the local variables inside a function are not static variables. To cause a local variable to have static storage duration you must explicitly mark it with 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
    }
}

这篇关于未命名的命名空间中自动初始化为0的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:43