Skip to content

[C++] How to Check The Variable Data Type with typeid()

Last Updated on 2021-10-22 by Clay

In C++, we always can be clear about the data type of the variables we declared; however, sometimes we passed in some parameters from third-party libraries, so we are not so sure which data type it is.

At this time, we can confirm the data type of the variable through typeid() in the standard library typeinfo.


The usage of typeid()

The typeid() function will return a type_info type, and you can also use .name() to return the system type name that is a C-style string, you can use printf("%s") to print it out.

The .name() results can refer the table:

Data Typename() return tag
boolb
charc
signed chara
unsigned charh
signed short ints
unsigned short intt
signed inti
unsigned intj
signed long intl
unsigned long intm
signed long long intx
unsigned long long inty
floatf
doubled
long doublee

In addition to these basic data types, there are many different types, such as STL and custom class. You can try it a little bit.


The following is a sample code:

#include <iostream>
#include <typeinfo>


int main() {
    // Init
    int a = 10;
    long int b = 100000;
    int c = 10;

    // typeid()
    const std::type_info &ai = typeid(a);
    const std::type_info &bi = typeid(b);
    const std::type_info &ci = typeid(c);

    // Print
    printf("a: %p | %s\n", &ai, ai.name());
    printf("b: %p | %s\n", &bi, bi.name());
    printf("c: %p | %s\n\n", &ci, ci.name());

    // Judge a == b
    printf("&ai == &bi: %d\n", &ai == &bi);                         // Not guaranteed
    printf("hash_code : %d\n\n", ai.hash_code() == bi.hash_code()); // Guaranteed

    // Judge a == c
    printf("&ai == &ci: %d\n", &ai == &ci);                         // Not guaranteed
    printf("hash_code : %d\n", ai.hash_code() == ci.hash_code());  // Guaranteed

    return 0;
}


Output:

a: 0x7fff8027dbe8 | i
b: 0x7fff8027dc88 | l
c: 0x7fff8027dbe8 | i

&ai == &bi: 0
hash_code : 0

&ai == &ci: 1
hash_code : 1

References


Read More

Tags:

Leave a Reply