Contenido del Curso
C++ Data Types
C++ Data Types
Void
In C++, you always have to specify the type because it is a statically-typed language. The compiler needs to know the exact type of each variable to allocate the correct amount of memory and to enforce type safety. It also needs to know the types of function return values and parameters.
Note
A statically-typed language is one where the data type of a variable is explicitly declared and enforced by the compiler.
main
#include <iostream> // Let's consider at a simple example. // Imagine you need to create a function that logges something in console // What type should it return? ___ log(std::string message) { std::cout << message; return ___; }
In this case, we do not need a specific type to be returned. It can be int
, double
, float
, or bool
it doesn't matter for this scenario. In fact, what if we don’t want to return anything at all?
Void as a Function Return Type
There are often functions that seems to not need to return anything like:
main
// Outputting infromation in console ___ log(std::string message) { std:: cout << message; } // Updating values for variables ___ update(int& variable, int new_value) { variable = new_value; } // Calling other function ___ closeFile(std::fstream& file) { file.close(); }
In this case we can use void
data type. The void
data type in programming signifies the absence of any value or type. It can be used in many different ways but for the function it is usually used to indicate that a function does not return any value.
main
#include <iostream> void log(std::string message) { std::cout << message; return; } int main() { log("This is a void function!"); }
Note
We used a
return
keyword but did not actually passed any value,return
keyword could also be omitted in thevoid
functions, try to erase it in the example.
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. They are really usefull but sometimes hard to understand. Look at the example
main
#include <iostream> int main() { int num = 10; // Here we are creating a void pointer // Now it can point to any variable of any data type // You can try changing the type of `num` from `int` to `float` void* ptr = # // To use this pointer, we need to cast it to the appropriate type // VVV int* intPtr = static_cast<int*>(ptr); std::cout << *intPtr << std::endl; // Output: 10 }
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.
¡Gracias por tus comentarios!