A Guide to "Void" in Computer Programming

Void functions are stand-alone statements

Students programming at computer in computer lab classroom
Caiaimage/Robert Daly / Getty Images

In computer programming, when void is used as a function return type, it indicates that the function does not return a value. When void appears in a pointer declaration, it specifies that the pointer is universal. When used in a function's parameter list, void indicates that the function takes no parameters. 

Void as a Function Return Type

Void functions, also called nonvalue-returning functions, are used just like value-returning functions except void return types do not return a value when the function is executed. The void function accomplishes its task and then returns control to the caller. The void function call is a stand-alone statement. 

For example, a function that prints a message doesn't return a value. The code in C++ takes the form:

void printmessage ( )
{
 cout << "I'm a function that prints a message!";
}
int main ( )
{
 printmessage ( );
}

A void function uses a heading that names the function followed by a pair of parentheses. The name is preceded by the word "void," which is the type.

Void as a Function Parameter

The void can also appear in the parameter list part of the code to indicate the function takes no actual parameters. C++ can take the empty parentheses, but C requires the word "void" in this usage. In C, the code takes the form:

void printmessage (void )
{
 cout << "I'm a function that prints a message!";

Note that the parentheses that follow the function name are not optional in any case.

Void as a Pointer Declaration

The third use of void is a pointer declaration that equates to a pointer to something left unspecified, which is useful to programmers who write functions that store or pass pointers without using them. Eventually, it must be cast to another pointer before it is dereferenced. A void pointer points to objects of any data type.

Format
mla apa chicago
Your Citation
Bolton, David. "A Guide to "Void" in Computer Programming." ThoughtCo, Aug. 28, 2020, thoughtco.com/definition-of-void-958182. Bolton, David. (2020, August 28). A Guide to "Void" in Computer Programming. Retrieved from https://www.thoughtco.com/definition-of-void-958182 Bolton, David. "A Guide to "Void" in Computer Programming." ThoughtCo. https://www.thoughtco.com/definition-of-void-958182 (accessed March 19, 2024).