C语言 有没有办法在 C 中打印出变量/指针的类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2160635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:19:00  来源:igfitidea点击:

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

ctypes

提问by Ritwik Bose

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 function that I can use like so:

或者我可以像这样使用的函数:

printf(gettype(x));

which would output:

这将输出:

struct b

采纳答案by manav m-n

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.

尝试使用 GDB 进行调试,它将打印与变量相关的所有属性,包括它的类型。但是,您的程序应该在使用 GDB 之前编译。

回答by Ariel

I have just discovered how to do this.

我刚刚发现了如何做到这一点。

printf("%d", variable);

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

如果变量不是 intgcc -Wall则将抱怨类型不匹配 - 并将打印出变量的类型,这正是您要查找的类型。

回答by Paul R

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

如果您使用的是 gcc 或 gcc 兼容的编译器,那么您可以使用(显然是非标准和不可移植的)typeof关键字,它的工作方式与 sizeof 非常相似。

回答by David Rodríguez - dribeas

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).

在 C 中,您在声明变量时提供了一个类型。这是编译器在抱怨赋值时拥有的唯一信息(也就是说,它不会使用对象的运行时类型,而是您拥有的静态类型)。

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.

转到代码,找到第 55 行,检查那里有哪些变量并找到代码中的类型。在 C 中甚至没有重载,类型就像在任何语言中一样静态和简单。