How to find out the type of variable C++
To determine the type of variable in C++ there is a function typeid().name() library typeinfo which must be pre-connected with
#include <typeinfo>
typeid().name()
Small demonstration
#include <string>
#include <iostream>
#include <typeinfo>
int main()
{
// Create four variables of different types
int int_var = 1;
float float_var = 1.0;
char char_var = '0';
std::string str1 = "www.heihei.ru";
// We will display the result of the typeid
std::cout << typeid(int_var).name() << std::endl;
std::cout << typeid(float_var).name() << std::endl;
std::cout << typeid(char_var).name() << std::endl;
std::cout << typeid(str1).name() << std::endl;
return 0;
}
The result
i f c NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
All four types are printed. GCC gives the mangled names: i is int, f is float, c is char, and the long line is std::string. Visual Studio prints the same types in full words.
In other languages
- C. : there is no such function.
-
C#
:
has a similar function
GetType()
-
Go
:
function
typeof
Available from the library reflect
Read the article: «How to determine the Go variable type»
-
Java
:
operator
instanceof
-
JavaScript
:
solves the problem
typeof()
Read the article: «How to determine the JavaScript variable type»
-
Python
:
similarity
type()
slightly different function
isinstance()
With the help of which you can solve the same problem.
Read the article: «How to determine the Python variable type»
The code on this page was run with g++ 15.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Andrei Olegovich