问题
I am surprised that a file containing the following lines of code is successfully compiled and linker produces an executable. I thought that all functions, except main
, must have a valid return
statement unless the return type is void
.
int foo(){}
double bar(){}
int main(){}
What am I missing?
回答1:
I thought that all functions, except
main
must have a valid return statement unless the return type isvoid
.
Yes, they must. You'll get undefined behaviour if they don't.
What am I missing?
If the function is sufficiently complicated, it can be difficult or impossible for the compiler to tell whether all return paths return a value; so the compiler isn't required to diagnose the error.
Most compilers will issue warnings in many cases, if you enable warnings.
回答2:
Not returning a value from a function that says it does is undefined behavior. It compiles and links, but don't expect the program to behave correctly.
If you compile with a high warning level, the compiler will tell you about it.
来源:https://stackoverflow.com/questions/22234357/is-there-a-default-return-value-of-c-functions