Home > Article > Backend Development > Why Does Omitting a Return Statement in a Non-Void C Function Sometimes Work (and Why It Shouldn\'t)?
Omitting Return Statement in C
In C , it is customary to terminate a non-void function with a return statement. However, a strange occurrence has been observed in a specific Windows version of g distributed with Strawberry Perl. This version allows the omission of a return statement in functions that return a non-void value, leading to unexpected behavior.
Consider the following member function:
struct boundTag Box::getBound(int side) { struct boundTag retBoundTag; retBoundTag.box = this; switch (side) { // set retBoundTag.bound based on value of "side" } }
This function is designed to return a structure representing bound tags. However, the developer inadvertently omitted the return statement:
// ... code from above }
When testing this function, the developer received valid output despite the missing return statement. Even after removing the return statement, the code compiles without any warnings.
The underlying issue is that omitting the return statement in a non-void function invokes undefined behavior. The ISO C -98 standard explicitly states that flowing off the end of a non-void function is equivalent to a return with no value, resulting in undefined behavior.
// ... code from above // Undefined behavior }
In this scenario, g likely returns a garbage value because the compiler cannot determine the intended return value. Using this returned value in your code is dangerous and can lead to unpredictable results.
Although g may not issue a warning by default, using the -Wall option during compilation forces the compiler to warn about these cases. This option will highlight the missing return statement and help prevent such undefined behavior.
Therefore, it is essential to always include a return statement in non-void functions, even if the return value is not used immediately. This practice ensures that the code conforms to the C standard and avoids any potential undefined behavior.
The above is the detailed content of Why Does Omitting a Return Statement in a Non-Void C Function Sometimes Work (and Why It Shouldn\'t)?. For more information, please follow other related articles on the PHP Chinese website!