Home > Software design >  Finding a way to identify data type of a variable in GCC
Finding a way to identify data type of a variable in GCC

Time:10-26

I believe my problem can be explained by the following code snippet

#define stingify(str) #str

int main()
{
    int a;
    printf("%s\n" , stringify(typeof(a)));
    return 0;
}

I want the typeof() macro to be expanded first then the stringify() macro to get my expected output "int" as a string. Is there any possible way for this?

CodePudding user response:

With pure standard C, you can use _Generic:

#define stringify_typeof(obj)  \
  _Generic((obj),              \
           int:    "int",      \
           double: "double")   \

If you want this type list more maintainable, you could move it into an X macro:

#include <stdio.h>

#define SUPPORTED_TYPES(X)     \
  X(int)                       \
  X(double)                    \
/* keep on adding types here */

#define GENERIC_LIST(type) ,type: #type
#define stringify_typeof(obj) _Generic((obj) SUPPORTED_TYPES(GENERIC_LIST) )

int main()
{
    int a;
    printf("%s\n" , stringify_typeof(a));

    double b;
    printf("%s\n" , stringify_typeof(b));

    return 0;
}

CodePudding user response:

You can use genetic macros if you want to print the type name.

char *typei()
{
    return "signed integer";
}

char *typeui()
{
    return "unsigned integer";
}

char *typef()
{
    return "float";
}

char *typeunk()
{
    return "unknown";
}

#define type(X) _Generic((X), \
        int: typei, \
        unsigned: typeui,  \
        float: typef,  \
        default: typeunk \
        )(X)
 
int main(void)
{
    const float y = 2.0f;

    printf("The type is: %s\n", type(y));
    printf("The type is: %s\n", type(3.0));
    printf("The type is: %s\n", type(3));
    printf("The type is: %s\n", type(3U));
    printf("The type is: %s\n", type(3LU));
}

Output:

The type is: float
The type is: unknown
The type is: signed integer
The type is: unsigned integer
The type is: unknown

https://godbolt.org/z/WMr5xs5os

  • Related