How to identify the type of variable in C?

Asked

Viewed 4,695 times

6

In languages such as Nodejs, Ruby, Moon, etc. When I want to know what the type of my variable is just use the function typeof (not necessarily in the cited languages) that returns a String with the type name of my variable.

But how to do it in C?

1 answer

5


The language C, does not have a macro capable of doing this, but from the gcc5 has the implementation of _Generic, that is able to issue a return from a variable type of.

#define typeof(var) _Generic( (var),\
char: "Char",\
int: "Integer",\
float: "Float",\
char *: "String",\
void *: "Pointer",\
default: "Undefined")

int main(){
    int x = 6;
    void *p = NULL;
    char *s = "text";
    printf("%s\n%s\n%s\n", typeof(x), typeof(p), typeof(s));
}

Exit:

>Integer
>Pointer
>String

Reference: cpp-Reference Generic

Browser other questions tagged

You are not signed in. Login or sign up in order to post.