In C programming, sometimes you encounter such a problem: the return value type of the function declaration and definition is void, but there is a return statement in the function body. This will cause a compilation error, because return statements cannot appear in void functions. So how do we solve this problem? This article will explain it to you in detail.
First, let's take a look at the sample code for this error:
void func() { // ... return 1; // ... }
In this code, we define a function func with a return value type of void. But within the function body, a return statement with a return value of 1 is used. In this case, the compiler will not be able to pass the code and will report an error:
error: return-statement with a value in function returning 'void' [-Werror,-Wreturn-type]
This error tells us that the return statement cannot be used in a function with a return value type of void.
So how to solve it? It's actually very simple, we just need to delete the return value from the return statement. The modified code is as follows:
void func() { // ... return; // ... }
Now, we change return 1 to return, which means no value will be returned. In this way, the function meets the requirement that the return value type is void, and the compiler can pass it normally.
In addition to the return statement, this problem may also occur in other places. For example, if you define a local variable with a return value type of void inside a function, and use the return statement in the function to return the value of the local variable, it will also cause a compilation error. In this case, we need to change the return value type of the local variable to another type.
In addition, there is a better solution, which is to use the auto keyword introduced in C 11 to infer the return value type of the function. This eliminates the need to manually specify the return value type. For example:
auto func() { // ... return 1; // ... }
In this example, we use the auto keyword to infer the return value type of the function. The compiler will infer the return value type to int because the return 1 statement is used in the function to return an integer value.
In short, when we encounter a function returning void in C writing, but there is an error in the return statement, we can solve this problem by deleting the value of the return statement or using the auto keyword to ensure that the function conforms to the return value Requirements of type void.
The above is the detailed content of C++ compilation error: The function returns void, but there is a return statement. How to solve it?. For more information, please follow other related articles on the PHP Chinese website!