what is void in c++
In C++, void is a special type keyword that means “no type” or
“nothing.” It is used in three main ways: as a function return type , as
a function parameter list , and as a pointer type (void*).
What void means conceptually
void does not represent any actual value; instead, it expresses the
absence of a type. For example, if a function returns void, it means the
function does a job but gives no value back to the caller.
1. void as a function return type
When you write:
cpp
void sayHello() {
std::cout << "Hello!\n";
}
the void says:
This function performs an action (writing text, changing variables, etc.), but it does not return anything.
You cannot use a void‑returning function in an expression like:
cpp
int x = sayHello(); // error: cannot assign nothing to an int
which the compiler will reject.
2. void in function parameters
In C++ you may see:
cpp
void doSomething(void);
Here, void in the parameter list means the function takes no arguments.
In modern C++ this is effectively the same as:
cpp
void doSomething();
(both mean “no parameters”).
This is more common in C than in C++, but the keyword still appears in some codebases and documentation.
3. void* as a generic pointer
void* is a pointer to unknown (untyped) data :
cpp
void* ptr;
int x = 42;
ptr = &x; // okay: void* can point to any data type
This means ptr can hold the address of any object, but it cannot be
dereferenced directly because C++ doesn’t know what type it points to. You
must cast it first:
cpp
int* p = static_cast<int*>(ptr); // cast back to int*
std::cout << *p << '\n';
This is useful in low‑level code, memory‑allocation functions, and APIs that need to work with arbitrary data.
A quick comparison table
Usage| Example| Meaning
---|---|---
void return type| void log();| Function runs but returns no value. 13
void in parameter list| void init(void);| Function takes no arguments. 35
void*| void* data;| Pointer to data of unknown type; cannot be
dereferenced directly. 36
Why void exists in C++
void formalizes the idea that some operations logically have no result
value , while still letting the type system distinguish them from functions
that return int, double, or objects. It also allows generic‑style pointer
handling via void*, which is widely used in C‑style APIs and system‑level
code.
If you tell me whether you’re coming from C, Python, or JavaScript, I can give
an analogy that maps void to what you already know.