Home > Backend Development > C++ > Why Does a C Function Without an Explicit `return` Statement Compile Without Error?

Why Does a C Function Without an Explicit `return` Statement Compile Without Error?

Patricia Arquette
Release: 2024-12-17 08:13:24
Original
515 people have browsed it

Why Does a C   Function Without an Explicit `return` Statement Compile Without Error?

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);
}
Copy after login

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]
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template