#022 – Using void as a function parameter

void is a special type. It means no type!

We are accustomed to functions returning void.

However, a function parameter can also be void. This means the function accepts zero parameters.

int getValue(void) {
	int x {};
	std::cin >> x;
	
	return x;
}

// getValue(void) is equivalent to getValue()

Why is this possible?

This feature is inherited from C for backwards compatibility reasons. In C, an empty parameter list in the function declaration means this function can accept anything. Literally anything. Although, it’s more apt to use the ellipsis syntax (...) to be explicit about the intent.

For C++, it’s best practice to leave the parameter list empty rather than populate it with void.

This is the perspective held by the C++ standard under 8.3.5 Functions:

A parameter list consisting of a single unnamed parameter of non-dependent type void is equivalent to an empty parameter list.

Also, if you have a sharp eye, you’ve probably noticed that we do int main() rather than int main(void).

Leave a Reply

Your email address will not be published. Required fields are marked *