Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this for loop stop? [duplicate]

I was trying to produce an error for a try-catch testing with this code, where I expected to get an error when accessing a[3] (fourth) element. Even when not getting the error, the for loop must stop after five iterations, which never occurs.

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

output:

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
like image 693
Adrian L Avatar asked Dec 14 '22 10:12

Adrian L


1 Answers

It's undefined behavior(UB), you don't have (at least) five elements in your array. You cannot catch UB, exceptions is what we catch. Nothing more to debate here, but see the interesting link in the comments section.

like image 134
LogicStuff Avatar answered Dec 29 '22 14:12

LogicStuff