统一的int值始终相同(C ++) [英] Unitialized int value always the same (C++)

查看:64
本文介绍了统一的int值始终相同(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

void main()
{
int x; 
cout << x;
system("pause");
}

当我调试这段代码时,它总是打印-858993460A.我读到它是因为VS将此设置为单元化var的默认值.但是我也读到在释放模式下,这应该是随机值.但是,每当我在发布模式下运行此代码时,我都会得到 1772893972A ,它不会改变->它不是随机的.这是什么?为什么我得到这个值?

When I debug this piece of code, it always prints -858993460A. I read that its because VS set this as default value for Unitialized vars. But I also read that in release mode, this should get random value. But everytime I run this code in release mode I get 1772893972A , which Is not changing -> its not random. What is this? Why do I get this value?

推荐答案

main 不是可执行文件的实际入口点,通常,实际入口点由运行时库获取(在VC ++中)绝对是这样),它执行一些CRT初始化任务,然后调用您的 main .该值可能是初始化代码执行的函数调用之一的剩余值.Debug和Release版本之间的差异可能是由于两种配置之间的初始化/堆栈管理不同.顺便说一下,这样的值总是相同的,这可能是它们来自某个参数/变量,每次都假定值相同.

The main is not the real entrypoint of the executable, in general the real entrypoint is taken by the runtime library (and in VC++ is definitely like that), which performs some CRT initialization tasks and then calls your main. That value is probably a leftover of one of the function calls performed by the initialization code; the difference between the Debug and Release builds is probably due to different initialization/stack management between the two configurations. By the way, it's just a chance that such vales are always the same, probably they are from some parameter/variable that assumes the same value every time.

如果不是那样的话,可能是进程内部其他一些初始化任务中的东西.它不是来自其他进程的东西,也不是发生在物理内存中的那个地方,因为Windows(运行您的应用程序的Windows)从不提供属于其他进程的内存页面而没有先将它们清空.

If it's not like that, it's probably stuff from some other initialization task internal to your process. It's not stuff from other processes or that just "happened" to be at that spot in physical memory, since Windows (on which your application is running) never gives memory pages that belonged to other processes without first blanking them.

仍然要记住,就标准而言,未初始化的变量具有"不确定的初始值"(第3.3.1节¶9),因此您不应依赖于这些值您可以通过读取未初始化的变量来获得.如果需要随机数,请使用适当的库函数.

Still, keep in mind that, as far as the standard is concerned, uninitialized variables have "indeterminate initial value" (§3.3.1 ¶9), so you should not rely on the values you may get by reading uninitialized variables. If you need random numbers, use the appropriate library functions.

我忘记了... void main 不是有效的C ++,它应该是 int main (第3.6.1节¶2,"返回类型为 int ").

I was forgetting... void main is not valid C++, it should be int main (§3.6.1 ¶2, "It shall have a return type of type int").

这篇关于统一的int值始终相同(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆