[Solved] Why this code work?


The C++ compiler can’t and won’t catch all the possible way you could write incorrect code.

And while running, a C++ program will usually not throw an error the moment you access memory out of bounds. The language was not designed to protect the programmer from doing bad things.

So when a program does something like this… which is undefined behavior… anything might happen. That “anything” can include appearing to work “correctly”. Or weird behavior might appear right away. But either way it’s wrong. If it appears to work, that’s only by luck.

And in practice it will also likely be corrupting memory somewhere which will lead to other problems eventually. Maybe the problems don’t have time to manifest in small example programs. But the larger the program, the more likely some kind of bad symptom will show up.

In the end, C++ puts a significant degree of responsibility on the programmer to write correct code which doesn’t do things like going outside of array bounds.

solved Why this code work?