Print Datatype of Variable to Console

To get the datatype of variable, use typeid(x).name() of typeinfo library. It returns the type name of the variable as a string.

Syntax

The syntax to get the type name of a variable x using typeid() is

typeid(x).name()

Example

In the following example, we take a variable x of type double, and print the type name of this variable programmatically using typeid() function.

C++ Program

#include <iostream>
#include <typeinfo>
using namespace std;

int main() {
    double x = 12;
    cout << "Type of x : " << typeid(x).name() << endl;
}

Output

Type of x : d
Program ended with exit code: 0

d stands for double.

Now, let us take a variable of user-defined class type, say Abc, and print the type of this variable programmatically.

C++ Program

#include <iostream>
#include <typeinfo>
using namespace std;

class Abc {};

int main() {
    Abc x = Abc();
    cout << "Type of x : " << typeid(x).name() << endl;
}

Output

Type of x : 3Abc
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned how to programmatically get the datatype of a variable in C++ and print the same, using typeid(), with examples.