Post

How to check the data type in C++

How to check the data type in C++

In C++, sometimes we need to check or inspect the type of a variable or expression. So I summarize some ways to implement it.

01 Use typeid

Through using the typeif operator from <typeinfo> to get the type information at runtime.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;

int main()
{
   string s;
   cout << typeid(s.c_str()).name() << endl;
}

Output: PKc

PKc is the mangled type used by Itanium C++ ABI(used by GCC/Clang) to represent a specific C++ type.

  • P -> Pointer(*)
  • K -> const qualifier
  • c -> char
This post is licensed under CC BY 4.0 by the author.