Dela via


typeof, __typeof__ (C23)

Operatorn är ny i C23-standarden och typeof är en unary-operator som returnerar typen av ett uttryck. Det kan användas i typdeklarationer, typgjutningar, typkontroller och så vidare. Den hämtar typen av en variabel, funktion eller valfritt C-uttryck.

Nyckelordet __typeof__ är ett Microsoft-specifikt tillägg som innehåller samma funktioner som typeof. Nyckelordet __typeof__ skiljer sig från typeof endast i och med att det är tillgängligt vid kompilering för alla versioner av C (inte bara /std:clatest), och det kan underlätta portningskoden mellan andra kompilatorer som stöder __typeof__.

typeof syntax

typeof(type)
typeof(constant-expression)
__typeof__(constant-expression)

typeof exempel

I det här exemplet används typeof(), men beteendet är detsamma om du använder __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;
}

Kravspecifikation

Kräver Visual Studio 17.9 eller senare, eller cl.exe version 19.39.33428 eller senare. Kompilera med /std:clatestom du vill använda typeof.

Se även

/std (Ange språkstandardversion)