Ready to practice?
Sign up to access interactive coding exercises and track your progress.
void Data Type
Understand when and why functions use void to indicate no return value or parameters.
The void type
The void type is the simplest data type in C++ - it represents the absence of a type.
Void is an incomplete type, meaning the compiler recognizes it but can't determine how much memory it needs. Since void represents "nothing," you cannot create variables of type void:
void data; // error: cannot create a variable of type void
Despite this limitation, void serves important purposes in C++.
Functions without return values
The most common use of void is to indicate that a function doesn't return any value:
void displayMessage(int count)
{
std::cout << "You have " << count << " messages\n";
// no return statement needed
}
If you attempt to return a value from a void function, the compiler will reject your code:
void printTotal(int amount)
{
std::cout << "Total: " << amount << "\n";
return amount; // error: cannot return a value from void function
}
Empty parameter lists
In C, void was used to explicitly indicate that a function accepts no parameters:
int readNumber(void) // C style - avoid this
{
int num{};
std::cin >> num;
return num;
}
While C++ compilers accept this syntax for backward compatibility, it's considered outdated. Modern C++ uses an empty parameter list instead:
int readNumber() // preferred C++ style
{
int num{};
std::cin >> num;
return num;
}
Use empty parentheses instead of void when declaring functions with no parameters.
Summary
Void has two primary uses:
- Indicating that a function doesn't return a value
- Advanced usage with pointers (covered in a later lesson)
void Data Type - Quiz
Test your understanding of the lesson.
Practice Exercises
Understanding void Functions
Create void functions that perform actions without returning values, demonstrating when to use void return type.
Lesson Discussion
Share your thoughts and questions
No comments yet. Be the first to share your thoughts!