In this C++ tutorial, you will learn how to print the datatype of a given variable using typeid(x).name() function of typeinfo library, with syntax and examples.

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()
ADVERTISEMENT

Example

1. Get datatype of a value (primitive datatype)

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.

2. Get datatype of an object (of user defined class type)

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.