Sorry if this is a noob question :( .
Piece of C code.
int array[5];
int cnt;
for(cnt = 0; cnt <= 10; cnt+=1)
{
array[cnt] = cnt;
}
Should give an error, right? No! Works fine! But why is that? It seems that -in the first line- an array of more than the double size (11) is defined. You can even access array[5 to 10] later on. And that is confusing me. It stops working when you define array[4 or less] ...
Thanks in advance.
It may happen to work with your particular compiler and computer, but you shouldn't count on it.
The behaviour of your code according to the C language specification is undefined. This means that it might do what you hope, or it might cause your computer to crash, or it might cause demons to fly out your nose.
Unlike higher-level languages such as Java and C#, C trusts you and does not perform explicit checks on the bounds of arrays. You are supposed to be responsible and not tread outside the boundaries of the array.
This only "works" if your definition of "works" is synonymous with "hasn't crashed yet".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With