Why doesn't this stop the loop?

I tried to create an error for try-catch testing with this code, where I expected to get an error while accessing an element a[3](fourth). Even if you don't get an error, the for loop should stop after five iterations, which never happens.

int a[3] = {1, 2, 3};
for(int i = 0; i < 5; i++)
{
    std::cout << i << ": " << a[i] << std::endl;
}

exit:

0: 1
1: 2
2: 3
3: 1970756548
4: 4201552
5: 2686800
6: 2130567168
7: 0
8: 0
9: 2686824
10: 4198992
.
.
.
4150: 0
4151: 0
4152: 0
4153: 0
4154: 0
+4
source share
3 answers

This is undefined behavior (UB), you do not have (at least) five elements in your array. You cannot catch UB, exceptions are what we are catch. There is nothing to discuss here, but check out the interesting link in the comments section.

+7
source

try-catch , [3] () . , for , .

. , ( ), . undefined.

, , undefined, .

+4

In fact, the simple answer is that you indicated the beginning of the array (address in memory), but continued to move forward from this address in memory - past the three elements of the array. C ++ allows you to go beyond the bounds of an array and will not give you an exception. The problem is that we do not know what will be in memory after three elements.

Here is a more detailed explanation of undefined behavior, which is referenced by other answers.

0
source

Source: https://habr.com/ru/post/1619393/


All Articles