Function Returning Undefined Value in C
In a code snippet that has surfaced in a library, a function named Min is defined as follows:
static tvec4 Min(const tvec4& a, const tvec4& b, tvec4& out) { tvec3::Min(a,b,out); out.w = min(a.w,b.w); }
Unexpectedly, this function compiles without error despite not returning a value, as its return type is not explicitly declared as void.
According to the C 11 draft standard, section 6.6.3, this behavior is undefined. The standard states that "flowing off the end of a function is equivalent to a return with no value" and that "this results in undefined behavior in a value-returning function."
In this scenario, the compiler is not obligated to provide an error or warning as it may be difficult to accurately diagnose the issue in all cases.
However, with the -Wall flag, both GCC and Clang can be prompted to generate a warning similar to:
warning: control reaches end of non-void function [-Wreturn-type]
To convert this warning into an error, ensuring a higher level of code quality, the -Werror=return-type flag can be utilized. Additionally, the -Wextra -Wconversion -pedantic flags are recommended for comprehensive error detection.
In Visual Studio, the aforementioned code would trigger error C4716:
error C4716: 'Min' : must return a value
In cases where not all code paths return a value, warning C4715 would be issued instead.
The above is the detailed content of Why Does a C Function Without an Explicit `return` Statement Compile Without Error?. For more information, please follow other related articles on the PHP Chinese website!