2

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

20
  • It si undefined behavior.:) Commented Apr 6, 2018 at 16:02
  • See Is uninitialized local variable the fastest random number generator? Commented Apr 6, 2018 at 16:03
  • 1
    You can't do that. There is no "junk" state in C/C++. This isn't SQL! An object either has a value you can read with any degree of predictability and definedness, or it doesn't. Commented Apr 6, 2018 at 16:17
  • 2
    @MartinC.Martin: How would you distinguish a random "junk value" from a valid value? Commented Apr 6, 2018 at 16:17
  • 1
    question is if this is automatic storage or process/thread storage? Default initialization for global array would be value initialization by zero. Commented Apr 6, 2018 at 16:24

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for sighting the spec! I'm not sure how I'll get around this, but maybe there's a way...
-3

Accessing any uninitialized data is undefined behavior.

5 Comments

I don't believe this is true for all types. See stackoverflow.com/a/11965368/2757035. The difference between "undefined" and "unspecified" is important.
@underscore_d that is a C question, this is a C++ version
@ShafikYaghmour Thanks for the nuance. So my point remains: some types produce at worst indeterminate values, not undefined.
@ShafikYaghmour: Reading an uninitialised unsigned char still isn't UB in C++, is it?
it is still undefined unless some other things are done... the clause in standard got bullet list when it yields undetermined result

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.