Can I find what type does a variable belongs, in C?
I'm a novice in C, and since C does some implict changing at times, I often get confused. I'm getting confused in what type
(like int,char
) does开发者_开发问答 the operation(+,-
) returns. So in C, I want to know what type
a variable belongs to at any point in a program. That is in Java we call it as Reflection and we can get all the information of our programs at runtime.
Now in C is there any lib that does the similar job of Reflection API in java. Or there is any trick in C, that can be used to find what type does a particular variable belongs to?
Any idea? Thanks in advance.
C and C++ are statically typed languages, so there is no reflection and no library for type discovery. In C, you just have to read the standard and understand the type promotion rules. Luckily, that's a finite amount of information that you should be able to grasp quickly.
In the new C++11, there's the decltype
keyword which returns the type of the expression, so you can say decltype(x + y) z = x + y;
to declare z
to be of the type of the expression x + y
. This is a compile-time construction, though, so this is merely a shortcut to something you could have inferred by other means.
If you use #include <typeinfo>
you can then use typeid
to get the variable type.
If your implementation supports C++ ABI, you can use it to print out expression types.
#include <iostream>
#include <typeinfo>
#include <cstdlib>
#include <cxxabi.h>
int main ()
{
int status;
char* mytypename = abi::__cxa_demangle(typeid((2+'x')*0.9f).name(), 0, 0,
&status);
if (mytypename && status == 0)
{
std::cout << mytypename << std::endl;
std::free (mytypename);
}
else
{
std::cerr << "Error determining type name, status is "
<< status << std::endl;
}
}
Such things are useful mostly for educational purposes. There's not much you can do with them, apart from looking and learning.
精彩评论