void
The void
data type plays a unique role. Unlike other fundamental data types such as int
, float
, and char
, void is used to indicate the absence of a specific type. It is often used in function declarations and pointers.
Void as a Function Return Type
When a function does not return a value, its return type is specified as void. For example.
main.cpp
In this example, the print
function does not return anything. It simply prints the specified message
to the console. But we get an error when we try to run the code.
This is because the function always has to return something when it is finished. Even if you return.
Note
Change the return type of the function from
int
to void.
Void as a Pointer
Void pointers (void*
) are pointers that do not have a specific data type associated with them. They can point to any type of object, but you must cast them to the appropriate type before using them. For example:
main.cpp
In this example, ptr
is a void pointer that points to an integer (num
). We then cast ptr to an int*
pointer to access and print the value of num.
Tudo estava claro?
Conteúdo do Curso
C++ Data Types
2. Numerical Data Types
4. Other Data Types and Concepts
C++ Data Types
void
The void
data type plays a unique role. Unlike other fundamental data types such as int
, float
, and char
, void is used to indicate the absence of a specific type. It is often used in function declarations and pointers.
Void as a Function Return Type
When a function does not return a value, its return type is specified as void. For example.
main.cpp
In this example, the print
function does not return anything. It simply prints the specified message
to the console. But we get an error when we try to run the code.
This is because the function always has to return something when it is finished. Even if you return.
Note
Change the return type of the function from
int
to void.
Void as a Pointer
Void pointers (void*
) are pointers that do not have a specific data type associated with them. They can point to any type of object, but you must cast them to the appropriate type before using them. For example:
main.cpp
In this example, ptr
is a void pointer that points to an integer (num
). We then cast ptr to an int*
pointer to access and print the value of num.
Tudo estava claro?