would have been had it existed

Status
Not open for further replies.

Pink_Flower

Junior Member
Joined
Apr 15, 2020
Member Type
Student or Learner
Native Language
Persian
Home Country
Iran
Current Location
United States
In this program, our array is of length 5, but we’re trying to write a prime number into the 6th element (index 5). C++ does not do any checking to make sure that your indices are valid for the length of your array. So in the above example, the value of 13 will be inserted into memory where the 6th element would have been had it existed. When this happens, you will get undefined behavior -- For example, this could overwrite the value of another variable, or cause your program to crash.

What does the bold part mean?

Source: https://www.learncpp.com/cpp-tutorial/62-arrays-part-ii/comment-page-5/#comment-465594
 
Computer programs store array values in consecutive memory locations. Suppose myArray[] is stored beginning in location 1001. It's defined as a five-element array, so its final element will be stored in location 1005. Your program has an instruction like myArray[6] = 13. This will place the value 13 in location 1006, overwriting whatever was there and causing unpredictable behavior. Location 1006 is where the sixth element would have been if the array had been declared as a six-element array.
 
Thank you so much for the comprehensive explanations.

The part also I still don't get is "had it existed"!

If the sentence was just "the value of 13 will be inserted into memory where the 6th element would have been existed", that would make sense to me but the structure 'had it existed' doesn't make sense at all.
 
Status
Not open for further replies.

Ask a Teacher

If you have a question about the English language and would like to ask one of our many English teachers and language experts, please click the button below to let us know:

(Requires Registration)
Back
Top