How to get the type of a variable in C++

In this tutorial, let’s discuss how to get the type of a variable in C++.

One way by which we can find out is by using Type Inference which will in return, return the data type of any variable or expression in

Type Inference helps for the deduction of the data type of a variable in a programming language.

We will start by declaring a variable

int a;
float b;
double f;

Now, to find the data type we will pass this variable as an argument.

typeid(a).name(); 

typeid(b).name();

typeid(f).name();

 

Get the type of a variable in C++

Below is the code to get the type of a variable in c++

#include <typeinfo>
#include <iostream>
int main() {
using namespace std;
    int a;  //declaring variable of type int
    float b; //declaring variable of type float
    double f =7.98; //declaring variable of type double

// we are passing the variable as a parameter in the function i.e typeid(variable_name)
    cout<<"\n type of a is: "<<  typeid(a).name(); 
    cout<<"\n type of b is:  "<< typeid(b).name();  
    cout<<"\n type of f is:  "<< typeid(f).name();
    return 0;
}

 

Output:

a is of type: i
b is of type: f
f is of type: d

I hope your all query regarding this is resolved now.

If you still have any query then please let me know.

 

In the above example,

We have declared the variable using the predefined datatype i.e Int, float, double, etc.

We can also declare the variable using the auto keyword and then get its data type.

Auto is the keyword for declaring the data type of any variable which will automatically decide which type of data is stored.

The method to declare any variable using auto keyword is quite similar as the way by which we declare the variable using int, float, double, etc.

i.e

int main()

  {

      auto variable_name;  // this will lead to allot the data type automatically to the variable.

}

Also, if you are using the auto keyword then you must include some libraries.

i.e

#include <bits/stdc++.h>

which support and contain information about the auto keyword.

I hope your all query regarding this is resolved now.

If you still have any query then please let me know.

You may also read :

Inheritance in C++

Leave a Reply