我是一個新的程序員,主要使用Code :: Blocks for C 。 我最近發現了關於typeof()
,因爲它被隱藏爲__typeof __() ,我想知道是否可以保存類型作爲typeof的結果。是這樣的:如何保存typeof的結果?
type a = __typeof__(?);
或者
#define typeof __typeof__
type a = typeof(?);
這可能嗎?
我是一個新的程序員,主要使用Code :: Blocks for C 。 我最近發現了關於typeof()
,因爲它被隱藏爲__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);
不,你不能使用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;
}
謝謝!我將我的編譯器更改爲c11並使用'_Generic'。 –
有沒有'標準C. typeof'操作你必須要閱讀* *編譯的文件(而不是代碼::塊IDE)瞭解更多信息。另外,*不要*做你想做的事情,在所有情況下99.99%不是你應該做的事情。也許如果你解釋*爲什麼*你想這麼做,那麼*實際問題*是你想要解決的問題,那麼我們可以幫你解決這個問題。 –
如果'var'具有類型'int',那麼'typeof(var)'是'int'。你可以說'輸入= int;'或任何類似的東西?這意味着什麼?你爲什麼需要這樣的東西? –
假設您想要在Java中編寫'Class c =「foo」.getClass();'的方法:忘記它,它不像C那樣工作。運行時沒有可用的類型信息。 –