我是一个新的程序员,主要使用Code :: blocks for C 99 。我最近发现了有关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);
no,您无法使用typeof
,例如t = (typeof(x) == int) ? a : b;
也无法使用int t = typeof(x);
。
如果您在C11下,_Generic
可以提供帮助:
#include <stdio.h>
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;
}