0

I'm trying to understand the concept of a fixed size in an array. Consider the following array:

int arr[1] = {0};

Now, if I subscript arr by any unsigned value greater than 0, I will get undefined values.

But if I do:

arr[1] = 42;

Now index 1 of arr holds 42. I can keep doing this assignment to any index of arr, making arr hold more than one int, which it was originally defined as.

How is arr having a fixed size if I can keep assigning multiple ints to its indices?

Train Heartnet
  • 785
  • 1
  • 12
  • 24
  • 1
    Welcome to the wonderful world of [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior) (also called UB). When you go out of bounds you will have UB. Just don't do it. – Some programmer dude Mar 28 '20 at 07:30
  • @ArminMontigny: Pretty new to C++! Guess I should have searched more diligently though (somehow it didn't cross my mind that the reassignment would be undefined behaviour!). – Train Heartnet Mar 28 '20 at 07:42
  • @Someprogrammerdude: Thanks so much, that clears it up! I was under the impression that accessing out-of-bounds indices would lead to just *undefined values* (which could be *made defined* by assignment). – Train Heartnet Mar 28 '20 at 07:42
  • This doesn't address the question, but `arr[1] = 42;` is not initialization; it's assignment. Initialization occurs when you **create** an object, as in `int arr[1] = {0};`. Yes, that initialization uses `=`, which makes it look similar to assignment, but `int arr[1] = {0};` does not use the assignment operator. – Pete Becker Mar 28 '20 at 14:58

0 Answers0