C++ Programs with Void Function
In C++, a function that does not return any value is called a void function. Void functions are commonly used when we need to perform an action without returning any value.
Syntax
void function_name(parameters) {
// code
}
The void
keyword indicates that the function does not return any value. The parameters
can be any number of input variables that the function may need to perform its action.
Example
#include <iostream>
using namespace std;
void printMessage(string message) {
cout << message << endl;
}
int main() {
printMessage("Hello World!");
return 0;
}
Output
Hello World!
Explanation
In the above example, we have defined a void function called printMessage
that takes a string parameter. The function simply prints the input message to the console. We then call this function from our main method by passing the string "Hello World!" as a parameter.
Use
Void functions can be used to perform any action that does not require returning a value. Some common uses of void functions include:
- Displaying messages or output to the console
- Updating or modifying global variables or objects
- Performing I/O operations like reading or writing to files and databases
Important Points
- Void functions do not return any value
- Void functions can have parameters
- Void functions are used to perform actions without returning any values
- Void functions can modify global variables or objects if needed
Summary
In summary, void functions in C++ are a useful tool for performing actions that do not require returning any values. They are commonly used for displaying messages, updating global variables, and performing I/O operations. Void functions can be defined with any number of parameters as needed to perform their action.