Check whether a variable is of a certain qualified type

suggest change
#include <stdio.h> 

#define is_const_int(x) _Generic((&x),  \
        const int *: "a const int",     \
        int *:       "a non-const int", \
        default:     "of other type")

int main(void)
{
    const int i = 1;
    int j = 1;
    double k = 1.0;
    printf("i is %s\n", is_const_int(i));
    printf("j is %s\n", is_const_int(j));
    printf("k is %s\n", is_const_int(k));
}
i is a const int
j is a non-const int
k is of other type

However, if the type generic macro is implemented like this:

#define is_const_int(x) _Generic((x), \
        const int: "a const int",     \
        int:       "a non-const int", \
        default:   "of other type")

The output is:

i is a non-const int
j is a non-const int
k is of other type

This is because type qualifiers are discarded from the type of the controlling expression of _Generic. The first macro avoids that by inspecting &x, so its argument must be an lvalue. The address of a const int has type const int *, which keeps the qualifier visible to the selection.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents