user3142434
user3142434

Reputation: 305

Weird C++ array initialization behaviour

The following code

int x;
cin >> x;
int b[x];
b[5] = 8;
cout << sizeof(b)/sizeof(b[0]) << endl << b[5];

with x inputted as 10 gives the ouput:

10
8

which seems very weird to me because:

According to http://www.cplusplus.com/doc/tutorial/arrays/ we shouldn't even be able to initialize an array using a value obtained from cin stream.

NOTE: The elements field within square brackets [], representing the number of elements in the array, must be a constant expression, since arrays are blocks of static memory whose size must be determined at compile time, before the program runs.

But that's not the whole story! The same code with x inputted as 4 sometimes gives the output

Segmentation fault. Core dumped.

and sometimes gives the output:

4
8

What the heck is going on? Why doesn't the compiler act in a single manner? Why can I assign a value to an array index that is larger than the array? And why can we even initialize an array using variable in the first place?

Upvotes: 1

Views: 211

Answers (1)

therainmaker
therainmaker

Reputation: 4343

I initially mentioned this as a comment, but seeing how no one has answered, I'm gonna add it here.

What you have demonstrated above is undefined behavior. It means that you can't tell what will the outcome be. As Brian adds in the comments, it will result in a diagnostic message (which could be a warning). Since the compiler would go ahead anyway, it can be called UB as it is not defined in the standard.

Upvotes: 2

Related Questions