C23 標準中的新功能,運算符是一元運算符, typeof 會傳回表達式的類型。 它可以用於類型宣告、類型轉換、類型檢查等等。 它會取得變數、函式或任何 C 運算式的類型。
關鍵詞 __typeof__ 是Microsoft特定擴充功能,可提供與 typeof相同的功能。 關鍵詞 __typeof__ 與 只有在編譯所有 C 版本時才有不同 typeof 之處, /std:clatest而且它可能會簡化支援 的其他編譯程式 __typeof__之間的程式代碼移植。
typeof 語法
typeof(type)
typeof(constant-expression)
__typeof__(constant-expression)
typeof 例
這個範例會使用 typeof(),但如果您使用 __typeof__,則行為會相同。
// Compile with /std:clatest
#include <stdio.h>
double func()
{
3.14;
}
#define POINTER(T) typeof(T*)
int main()
{
auto a = func(); // the type for a (double) is inferred, but requires initialization at point of declaration
typeof(func()) b; // the type for b is double, but didn't have to be initialized at point of declaration
// Some declarations using typeof
POINTER(int) p1 = NULL; // p1 is int*
typeof(double(void))* pFunc = func; // pFunc is a pointer to a function that takes no arguments and returns a double
printf("pFunc() returns %f\n", pFunc());
return 0;
}
需求
需要 Visual Studio 17.9 或更新版本,或 cl.exe 19.39.33428 版或更新版本。
若要使用 typeof,請使用 編譯 /std:clatest。