简体   繁体   中英

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

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.)

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.

访问任何未初始化的数据是未定义的行为。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM