问题
I am a new programmer that is mostly using Code::Blocks for C99.
I recently found out about the typeof()
because it was hidden as __typeof __()
and I wanted to know if you can save a type as a result of typeof. something like:
type a = __typeof__(?);
Or
#define typeof __typeof__
type a = typeof(?);
Is this possible?
回答1:
You should avoid typeof
or __typeof __()
since they aren't standard C. The latest C version (C11) has support for this through the _Generic
keyword which works in the same manner.
There is no "type type" in C but you can easily make one yourself:
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);
回答2:
No, you can not use typeof
like t = (typeof(x) == int) ? a : b;
nor int t = typeof(x);
.
If you are under C11, _Generic
can help:
#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;
}
来源:https://stackoverflow.com/questions/42222379/how-to-save-the-result-of-typeof