C++ void
Created By: chatGPT
In C++, the
void
keyword is used to specify that a function does not return a value. This is useful when you want to perform an operation without needing to send any information back to the caller. Here’s an example of how to declare a function with a void
return type: void displayMessage() {
std::cout << "Hello, World!" << std::endl;
}
To call a
void
function, simply write its name followed by parentheses. Since it doesn’t return a value, you cannot use it in an expression. Here’s how you can call the displayMessage
function: int main() {
displayMessage(); // This will call the function
return 0;
}
You can also have
void
functions that take parameters. This allows you to customize the behavior of a function without returning a value. Here’s an example: void greetUser(std::string name) {
std::cout << "Hello, " << name << "!" << std::endl;
}
In this example, the
greetUser
function takes a string
parameter and uses it to greet the user. You can call this function like this: int main() {
greetUser("Alice"); // Output: Hello, Alice!
return 0;
}