开发者

Is there a way to print out the type of a variable/pointer in C?

I want to print out (or otherwise ascertain) the type of some variable in my program. Is there a good way to do it? By good, I mean a way that works, even if it means intentionally throwing compiler errors.

For example:

client.c:55: error: incompatible types in assignment

is the error I'm getting right now. What I WANT is it to tell me something like:

client.c:55: error: attempting to assign type struct a to type struct b

or a f开发者_运维问答unction that I can use like so:

printf(gettype(x));

which would output:

struct b


I have just discovered how to do this.

printf("%d", variable);

If variable is not an int then gcc -Wall will complain that the types don't match - and will print out the type of the variable, which is exactly what you are looking for.


try debugging using GDB, it will print all properties associated with the variable including it's type. But, your program should compile before using GDB.


In C you provide a type when you declare a variable. That is the only information that the compiler has when it is complaining about the assignment (that is, it will not use the runtime type of the object, but the static type you have).

Go to the code, locate line 55, check what variables are there and find the types in the code. In C there are not even overloads, types are as static and simple as it gets in any language.


If you debug with gdb. Then you can set a breakpoint with: break line_number to break execution where you want to fetch that variable type. And from then you can print the type of a variable in gdb with: ptype your_variable_name or whatis your_variable_name The last one will print the type of the variable as well as the definition you gave it.


If you're using gcc or a gcc-compatible compiler then you can use the (obviously non-standard and non-portable) typeof keyword, which works much like sizeof.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜