Failing to return a value from a function that has a non-void
return type results in undefined behaviour, but is not a semantic error.
The reason for this, as far as I can determine, is largely historical.
C originally didn't have void
and implicit int
meant that most functions returned an int
unless explicitly declared to return something else even if there was no intention to use the return value.
This means that a lot of functions returned an int but without explicitly setting a return value, but that was OK becase the callers would never use the return value for these functions.
Some functions did return a value, but used the implicit int
because int
was a suitable return type.
This means that pre-void
code had lots of functions which nominally returned int
but which could be declared to return void
and lots of other functions that should return an int
with no clear way to tell the difference. Enforcing return
on all code paths of all non-void
functions at any stage would break legacy code.
There is also the argument that some code paths in a function may be unreachable but this may not be easy to determine from a simple static analysis so why enforce an unnecessary return
?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…