English 中文(简体)
初始化空字符串时初始化的int的值不同[重复]
原标题:Value for initialized int is different when empty string initialized [duplicate]
  • 时间:2023-08-05 02:55:38
  •  标签:
  • c++

我有以下功能:

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在第二个函数中不为零吗?

问题回答

你的标题提到了一个初始化的int,但实际上不是。

声明<code>int local_int(在源代码中有(1))声明了一个未初始化的整数,该整数可以有任何任意值,它是合法的,它是314159,因为它是零。

如果希望有一个特定的值,只需用以下内容初始化即可:

int local_int = 42;

(1)如果它在代码的其他地方(例如在文件级别),则规则不同,并且它可能是默认初始化的。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签