[Solved] Why do I get output “5”?


This program is invalid (further explanation of why follows below).

In C89 when you call m(), or in C99 when you start the program at all, undefined behaviour is caused. This means anything can happen. To put it another way, the compiler only has to cope with correct programs; and if you make a mistake then you can get junk results happening (this is not just limited to invalid output).

In C89 this code actually does not require any compiler diagnostics1. It just causes undefined behaviour. (Helpful compilers may give you a warning anyway.)

This is because the line int k = m(); causes implicit declaration of a function m() returning int and taking unspecified arguments. However, the actual function body of m returns void. This means that if m is ever called, then undefined behaviour is triggered.

In practical terms, what you may be experiencing is that the main function looks in a particular register for the value returned from m, but the function body of m did not set that register, and it happened to contain 5 by chance. Do not rely on this behaviour.

Since you did not use function prototypes, the compiler is not required to diagnose this error. If you did use a function prototype (e.g. void m(void)), or if you move void m() to be before main() then the compiler is required to give a diagnostic. (If you then go on to run your program anyway , ignoring this message, then the entire behaviour of the program is undefined).

In C99 , implicit declaration of functions was removed, and the line int k = m(); must give a diagnostic.


1 requires a diagnostic means that the code has an error according to Standard C, and the compiler must report a message to you. The compiler may choose to categorize this message as “warning” and produce an executable anyway, however the code is still incorrect in this scenario and should be fixed.

14

solved Why do I get output “5”?