如何保存typeof的结果?
How to save the result of typeof?
我是一名新程序员,主要使用 Code::Blocks for C99。
我最近发现了 typeof()
因为它被隐藏为 __typeof __()
我想知道您是否可以通过 typeof 保存类型。类似于:
type a = __typeof__(?);
或者
#define typeof __typeof__
type a = typeof(?);
这可能吗?
您应该避免使用 typeof
或 __typeof __()
,因为它们不是标准的 C。最新的 C 版本 (C11) 通过在同样的方式。
C 中没有 "type type",但您可以轻松地自己制作一个:
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;
或 int t = typeof(x);
那样使用 typeof
。
如果你在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;
}
我是一名新程序员,主要使用 Code::Blocks for C99。
我最近发现了 typeof()
因为它被隐藏为 __typeof __()
我想知道您是否可以通过 typeof 保存类型。类似于:
type a = __typeof__(?);
或者
#define typeof __typeof__
type a = typeof(?);
这可能吗?
您应该避免使用 typeof
或 __typeof __()
,因为它们不是标准的 C。最新的 C 版本 (C11) 通过在同样的方式。
C 中没有 "type type",但您可以轻松地自己制作一个:
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;
或 int t = typeof(x);
那样使用 typeof
。
如果你在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;
}