Using the void keyword - C++

Some functions do not necessarily return a value. Maybe the only purpose of one of your functions is to display some text. In this case, you do not need a return value.

Unlike arguments, if you don’t have a return value, you cannot just leave the space before the function name blank in the function declaration or definition.

Here is where the void keyword comes into play. void is similar to zero in that it represents no value. For a non-returning function, put the term void where the return type would be:

However, if you do this, you need to make sure that you do not try to return a value in your function. You can, however, have an empty return statement, as shown here:

return;

This statement terminates the function. An empty return statement for a void function is not required. If there are no return statements, the function ends when it runs out of code.

If your function has no arguments (regardless of whether it has a return value), you can use the void keyword as the argument list instead of leaving that field blank. You don’t gain a particular advantage either way.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C++ Topics