How do i properly identify a type of variable in c++. I tried this to identify a type of variable :
int a = 5;
std::cout << typeid(a).name() << std::endl;
And instead of the expected output int, it gives you:
i
I Am Very confused on why that is happening.. Its somehow giving you only the first letter of the type you are declaring the variable. Int is not the only one... also this:
char a = 'A'
std::cout << typeid(a).name() << std::endl;
Is there a simple workaround to this? Any Help would be appreciated!
There are two problems with your code,
Firstly typeid(..).name()
returns an implementation defined string, it can be any valid string, it could return ""
for every type, it could even return different values for each program execution (though I believe the value can't change during execution). GCC (and Clang?) return unreadable names, whereas Visual C++ returns reasonable ones (in this case int
)
Secondly if the type of a
is a polymorphic type, typeid(a)
will return the typeid
corresponding to the dynamic type of a
and not the type that was used to declare a
, instead use typeid(decltype(a))
.
Unfortunately there is no standard way of getting the name of a type in a way that is human readable or correct C++ syntax. (see Unmangling the result of std::type_info::name if you want a way that works in GCC)
EDIT Using Boost, you could try std::cout << boost::typeindex::type_id<decltype(a)>().pretty_name() << std::endl;
, see Getting human readable and mangled type names