Page 188 - C-Language
P. 188

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.


        Type-generic printing macro


         #include <stdio.h>

         void print_int(int x) { printf("int: %d\n", x); }
         void print_dbl(double x) { printf("double: %g\n", x); }
         void print_default() { puts("unknown argument"); }

         #define print(X) _Generic((X), \
                 int: print_int, \
                 double: print_dbl, \
                 default: print_default)(X)

         int main(void) {
             print(42);
             print(3.14);
             print("hello, world");
         }


        Output:


         int: 42
         double: 3.14
         unknown argument


        Note that if the type is neither int nor double, a warning would be generated. To eliminate the
        warning, you can add that type to the print(X) macro.


        Generic selection based on multiple arguments


        If a selection on multiple arguments for a type generic expression is wanted, and all types in
        question are arithmetic types, an easy way to avoid nested _Generic expressions is to use addition
        of the parameters in the controlling expression:


         int max_int(int, int);
         unsigned max_unsigned(unsigned, unsigned);



        https://riptutorial.com/                                                                             164
   183   184   185   186   187   188   189   190   191   192   193