Is it possible to print a variable"s type in standard C++?

Can You Print a Variable's Type in C++? 🤔
Have you ever wondered if it's possible to print the type of a variable in C++? Maybe you find yourself in a situation where you need to debug your code or simply understand the type of a variable during runtime. Well, the good news is that there is a simple solution to this problem!
The Challenge: Printing a Variable's Type 📝
Let's take a look at an example to better understand the challenge at hand:
int a = 12;
cout << typeof(a) << endl;In this code snippet, we have a variable a of type int. The intention is to print the type of the variable a using cout.
The expected output of this code would be:
intHowever, if you run this code as is, you'll quickly discover that there is a problem. You might encounter an error similar to:
error: use of undeclared identifier 'typeof'Now, let's explore the solution to this problem!
Solution: Using typeid and name() 🚀
To print the type of a variable in C++, we can make use of the typeid operator in combination with the name() function.
#include <iostream>
#include <typeinfo>
int main() {
int a = 12;
const std::type_info& type = typeid(a);
std::cout << type.name() << std::endl;
return 0;
}Running the above code will yield the expected result:
iIn this solution, we include the <typeinfo> header to gain access to the necessary functionality. Then, we define a variable type of type const std::type_info& and assign it the result of typeid(a). This retrieves the type information of variable a.
Finally, by calling type.name(), we obtain a const char* containing the name of the type. In this case, i represents the int type.
Take It Further: Printing Other Types 🎉
The use of typeid and name() is not limited to only primitive types. You can also use it with other types such as classes, structures, or even user-defined types!
Let's see an example with a class:
#include <iostream>
#include <typeinfo>
class MyClass {
// class implementation goes here
};
int main() {
MyClass obj;
const std::type_info& type = typeid(obj);
std::cout << type.name() << std::endl;
return 0;
}When executing this code snippet, you will get an output similar to:
7MyClassHere, 7MyClass indicates that the type of obj is the class MyClass. The 7 corresponds to the number of characters in the class name.
Share Your Discoveries! 🌟
Knowing how to print the type of a variable can be incredibly useful for debugging or understanding code during runtime. Now that you have this knowledge, go ahead and share it with your fellow developers! They might find it handy as well.
If you have any questions, suggestions, or want to learn more about C++, leave a comment below. Let's start a conversation and improve our coding skills together!
Keep coding! 🚀
Take Your Tech Career to the Next Level
Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.


