Is there a default return value of C++ functions? [duplicate]

房东的猫 提交于 2021-02-04 18:41:08

问题


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 is void.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!