In C++, is accessing an uninitialized array unspecified behavior or undefined behavior?

冷暖自知 提交于 2019-12-13 02:51:43

问题


For example, in the following code:

int myarray[3];
int x = myarray[1];

Is the code guaranteed to execute successfully in constant time, with x having some integral value? Or can the compiler skip emitting code for this entirely / emit code to launch GNU Chess and still comply with the C++ standard?

This is useful in a data structure that's like an array, but can be initialized in constant time. (Sorry, don't have my copy of Aho, Hopcroft and Ullman handy so can't look up the name.)


回答1:


It's undefined behavior.

According to the standard ([dcl.init] paragraph 12),

If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced ... If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases

with all the following cases addressing access of unsigned narrow character type or std::byte, which can result in an indeterminate value instead of being undefined.




回答2:


Accessing any uninitialized data is undefined behavior.



来源:https://stackoverflow.com/questions/49696810/in-c-is-accessing-an-uninitialized-array-unspecified-behavior-or-undefined-be

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