Table of Contents
A void function is a function that does not return a value to its caller. The void keyword is specified as the function’s return type to indicate that the function performs an operation without producing a return value.
A void function can still accept parameters and perform calculations or other operations. When execution reaches the end of the function body, control returns to the calling code.
Source Code #
#include <iostream>
void displayMessage()
{
std::cout << "Welcome to C++.\n";
}
int main()
{
displayMessage();
return 0;
}
Output #
Welcome to C++.
Explanation #
void displayMessage()defines a function nameddisplayMessagewith no return value.voidspecifies that the function does not return a value to its caller.displayMessage();calls the function frommain().- The statement inside the function body executes when the function is called.
- A
voidfunction does not require areturnstatement to return a value. - A
return;statement without a value can still be used in avoidfunction to terminate the function early. - After reaching the end of the function body, control returns to the statement following the function call.
return 0;terminates the program successfully.