- Learn C++ - https://www.learncpp.com -

4.2 — Void

Void is the easiest of the data types to explain. Basically, void means “no type”!

Consequentially, variables can not be defined with a type of void:

Void is typically used in several different contexts.

Functions that do not return a value

Most commonly, void is used to indicate that a function does not return a value:

If you use a return statement to try to return a value in such a function, a compile error will result:

On Visual Studio 2017, this produced the error:

error C2562: 'noReturn': 'void' function returning a value

Deprecated: Functions that do not take parameters

In C, void is used as a way to indicate that a function does not take any parameters:

Although this will compile in C++ (for backwards compatibility reasons), this use of keyword void is considered deprecated in C++. The following code is equivalent, and preferred in C++:

Best practice

Use an empty parameter list instead of void to indicate that a function has no parameters.

Other uses of void

The void keyword has a third (more advanced) use in C++ that we cover in section 9.20 -- Void pointers [1]. Since we haven’t covered what a pointer is yet, you don’t need to worry about this case for now.

Let’s move on!

4.3 -- Object sizes and the sizeof operator [2]
Index [3]
4.1 -- Introduction to fundamental data types [4]