Accessing array elements beyond array boundaries (before 0
or from its size up) is undefined behavior. It may or may not produce values, it may cause the program to end abruptly, it may cause your system to stop, restart or catch fire...
Modern systems try to confine undefined behavior within reasonable limits via memory protection, user space limitations etc. but even user space code errors can have dire consequences:
- pacemaker messing with its timing values can cause premature death ;
- banking software overflowing array boundaries can overwrite account balance information crediting some random account with untold amounts of dollars.
- your self driving car could behave worse than drunk drivers...
- think of nuclear power-plant control software, airplane instruments, military stuff...
There is no question undefined behavior should be avoided.
Regarding the exit status, your program uses an obsolete syntax for the definition of main()
, implicit return type, which is no longer supported in C99 and later, but does not return anything, which means its return value can be any random value, including a different value for every execution. C99 specified a kludge for the main()
function and forces an implicit return 0;
at the end of main()
, but relying on it is bad style.
Similarly, invoking printf()
without a proper prototype is undefined behavior. You should include <stdio.h>
before the definition of function main()
.
Lastly, ar[0]
and ar[1]
are initialized in main()
, but ar[2]
and ar[3]
are not. Be aware that accessing uninitialized values also has undefined behavior. The values can be anything at all, what you describe as random values, but on some systems, they could be trap values, causing undefined behavior by just reading them.
Some very handy tools are available to track this kind of problems in simple and complex programs, most notably valgrind
. If you are curious about this subject, You should definitely look at it.