已初始化的整数的值与空字符串初始化时不同。

huangapple go评论43阅读模式
英文:

Value for initialized int is different when empty string initialized

问题

我有以下的函数:

int main()
{
    int local_int;
    std::cout << local_int << std::endl;
    return 0;
}

这个函数会打印出 0

但是下一个函数:

int main()
{
    int local_int;
    std::string local_str;
    std::cout << local_int << std::endl;
    std::cout << local_str << std::endl;
    return 0;
}

打印出:

21930

(第二行是空字符串)

有人可以帮助我理解这两个函数之间发生了什么,为什么第二个函数中的 local_int 不是零吗?

英文:

I have the following function:

int main()
{
    int local_int;
    std::cout &lt;&lt; local_int &lt;&lt; std::endl;
    return 0;
}

which prints 0.

But the next function:

int main()
{
    int local_int;
    std::string local_str;
    std::cout &lt;&lt; local_int &lt;&lt; std::endl;
    std::cout &lt;&lt; local_str &lt;&lt; std::endl;
    return 0;
}

prints

21930

(the second line is the empty string)

Can someone help me understand what is going on between the two functions and why local_int isn't zero in the second function?

答案1

得分: 3

你的标题提到了一个已初始化的整数,但实际上并不是这样的。

声明 int local_int;(在源代码中的位置如下)声明了一个未初始化的整数,它可以具有任何任意的值,它可以是314159,也可以是零。

如果你希望它具有特定的值,只需使用以下方式进行初始化:

int local_int = 42;

(1)这是因为它具有自动存储期。如果它具有不同的存储期,它将遵循不同的规则,可能会被默认初始化或零初始化。但在这个简单的非static函数内的int声明中,情况并非如此。

有关不同存储期的更多信息以及它们如何被初始化(或被初始化),在ISO C++标准中有详细的描述 已初始化的整数的值与空字符串初始化时不同。

英文:

Your title mentions an initialised int, but it really is not.

The declaration int local_int; (where you have it<sup>(1)</sup> in the source code) declares an uninitialised integer which may have any arbitrary value, it's as legal for it the be 314159 as it is to be zero.

If you want it to have a specific value, simply initialise it with something like:

int local_int = 42;

<sup>(1)</sup> This is because it is automatic storage duration. If it had a different storage duration, it would follow different rules and may be default- or zero-initialised. But that is not the case with this simple non-static int declaration within a function.

More information on the different storage durations, and how they are initialised (or not), are covered in the ISO C++ standard in excruciating detail 已初始化的整数的值与空字符串初始化时不同。

huangapple
  • 本文由 发表于 2023年8月5日 10:55:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定