Reading uninitialized variable [duplicate]

╄→гoц情女王★ 提交于 2020-01-16 18:05:47

问题


Reading uninitialized variables leads to undefined behavior, e.g.

#include <iostream>

int main()
{
    int a;
    std::cout << a << std::endl; // undefined behavior
}

Can someone give a formal explanation of this fact?


回答1:


Here is the relevant section, I think:

4.1 Lvalue-to-rvalue conversion

1 - A glvalue of a non-function, non-array type T can be converted to a prvalue. If T is an incomplete type, a program that necessitates this conversion is ill-formed. If the object to which the glvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior.

A variable is an lvalue, and I think an "lvalue to rvalue conversion" is the process of taking a variable's value.

(Note - I'm not familiar with the C++ standards, so I may have not found the part that applies to this example. All I did was search the PDF for "uninitialized", and look for the hit that looks most relevant.)



来源:https://stackoverflow.com/questions/30542801/reading-uninitialized-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!