如何保存typeof的结果?

我是一个新的程序员,主要使用Code :: Blocks for C 99 。 我最近发现了typeof()因为它被隐藏为__typeof __(),我想知道你是否可以因typeof而保存一个类型。 就像是:

 type a = __typeof__(?); 

要么

 #define typeof __typeof__ type a = typeof(?); 

这可能吗?

你应该避免使用typeof__typeof __()因为它们不是标准的C.最新的C版本(C11)通过_Generic关键字以相同的方式支持这一点。

C中没有“类型类型”但你可以自己轻松制作一个:

 typedef enum { TYPE_INT, TYPE_FLOAT, TYPE_CHAR } type_t; #define get_typeof(x) \ _Generic((x), \ int: TYPE_INT, \ float: TYPE_FLOAT, \ char: TYPE_CHAR ); ... float f; type_t type = get_typeof(f); 

不,你不能像t = (typeof(x) == int) ? a : b;那样使用typeof t = (typeof(x) == int) ? a : b; t = (typeof(x) == int) ? a : b; 也不是int t = typeof(x);

如果您在C11下, _Generic可以提供帮助:

 #include  enum {TYPE_UNKNOWN, TYPE_INT, TYPE_CHAR, TYPE_DOUBLE}; #define type_of(T) _Generic((T), int: TYPE_INT, char: TYPE_CHAR, double: TYPE_DOUBLE, default: 0) int main(void) { double a = 5.; int t = type_of(a); switch (t) { case TYPE_INT: puts("a is int"); break; case TYPE_CHAR: puts("a is char"); break; case TYPE_DOUBLE: puts("a is double"); break; default: puts("a is unknown"); break; } return 0; }