C Language Generic selection Check whether a variable is of a certain qualified type

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

#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));
}

Output:

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 all type qualifiers are dropped for the evaluation of the controlling expression of a _Generic primary expression.



Got any C Language Question?