1

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?

7
  • 2
    I think this is what undefined behavior means. You can't tell what it'll do. Commented Oct 1, 2015 at 17:14
  • 3
    It is a C99 feature but several compilers support in C++ as an extension. Accessing an array out of bounds is undefined behavior, don't do it. Commented Oct 1, 2015 at 17:16
  • @Shafik Yaghmour thanks, this message has helped me understand what's going on Commented Oct 1, 2015 at 17:33
  • @therainmaker It's not UB. It's required to be diagnosed. Commented Oct 1, 2015 at 17:39
  • @Brian : What do you mean 'its required to be diagnosed'? Commented Oct 1, 2015 at 17:40

1 Answer 1

2

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.