Return cannot have a parameter in function returning void

In most programming languages, the return keyword is used to specify the value that a function should output. However, in the case of a function with a return type of void, the return keyword is used to exit the function without returning any value.

The “cannot have a parameter in function returning void” error occurs when a function with a return type of void is mistakenly given a parameter. Since a void function does not return any value, it does not make logical sense to have a parameter in such a function.

Here’s an example to illustrate this error:


        void printMessage() {
            String message = "Hello, world!";
            return message; // Error: cannot have a parameter in function returning void
        }
    

In the above example, the function “printMessage” is defined with a return type of void. However, the return statement is mistakenly trying to return a value (the “message” variable). This is not allowed and results in a compilation error.

To fix this error, you can remove the invalid return statement or change the return type of the function to something other than void if a value needs to be returned.

Similar post

Leave a comment