4 ms·
As far as I understand, there is no “expected behavior of main without a return” under ANSI; it’s undefined behavior as (according to this version of the C stan
by NobodyNada 5y ago
As far as I understand, there is no “expected behavior of main without a return” under ANSI; it’s undefined behavior as (according to this version of the C standard) a function with an int return type must return an int. The fact that it happens to return the result of last function call is more-or-less a coincidence because the compiler doesn’t bother to clear out or reuse the return value register.
If this seems unintuitive, consider a more general example:
int foo(int x) {
if (x >= 0) return 123;
if (x < 0) return 456;
}
What’s the “expected” return value if neither of the if-statements match? That seems like a nonsensical question because the conditions are clearly mutually exclusive, but if you’re a dumb enough compiler (or the conditions are more complex) you might not be able to prove that. So should it return zero? Should the compiler insert code to save and remember the result of the last function call? According to the C standard, the compiler doesn’t have to handle this situation; it is free to assume that the branches are indeed mutually exclusive, and it will most likely do whatever produces the easiest/fastest code in that case.
In the OP’s example, it seemingly just decides to return void (leaving whatever garbage was previously in the return value register for the caller to discover). But it could also have assumed that main must infinitely loop (since there’s no return statement), and omitted the return instruction altogether causing execution to “fall off” the end of the function into whatever happened to be next in memory.
- deleted 5y ago[deleted]
- pif 5y ago> As far as I understand, there is no “expected behavior of main without a return” under ANSI; it’s undefined behavior You are right. There are still a lot of so-called developers who cannot understand the concept of _undefined_ behavior.
- deleted 5y ago[deleted]
- _kst_ 5y agoNo, it's not undefined behavior. Only the status returned to the host environment is undefined. (And in C99 and later, the status is 0.) As for your example: int foo(int x) { if (x >= 0) return 123; if (x < 0) return 456; } that has undefined behavior only if the caller uses the value. (That's to cater to ancient C code written before the void type was introduced.)