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
int float char class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > C:\Users\ao\source\repos\typeid\x64\Debug\typeid.exe (process 132920) exited with code 0. Press any key to close this window . . .
All four types are defined.
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»
Article author: Andrei Olegovich