C C11 standart _Generic keyword


In C standart c11 is supported new keyword _Generic. It add way how we can add at macro level decisitions about variable types. And now is possible make some C++ like function "overloading". Here is some variants how to use this generic "_Generic". Now could print variables dont looking on its type _Generic will deal with it.


Detect type

#define type_str(T) _Generic( (T), int: "int",\
long: "long",\
default: "Unknown type")

Now we have define check for 2 types int and long. If there is some type undefined then choose default type and print "Unknown type". This is auto printf example where you can detect type and print its name. But as in page [1] you can add number values and compare types in simple way.

printf("Type1 %s\n", type_str('a'));
printf("Type2 %s\n", type_str(1));
printf("Type3 %s\n", type_str(1l));
printf("Type4 %s\n", type_str(0.0f));

Also is possible to use generic for 2 or more types but then amount of declaration grows. But it means that now according to params we can choose best function.

#define type_str2(T1,T2) _Generic( (T1),\
int: _Generic((T2),int:"int int", default: "int UNK"),\
default: "UNK UNK" )

printf("Double Type 1 %s\n", type_str2(1,1));
printf("Double Type 2 %s\n", type_str2(1,0.0f));
printf("Double Type 3 %s\n", type_str2(.0f,.0f));

Check if types is compatible

Strange but some types could be invalid if there is const used, like 'int' and 'const int'.

#define is_compatible(x,T) _Generic((x), T:"compatible",\
default: "non-compatible")

Here is defined 2 types and only (int and int) and (const int and const int) is compatible.

int i1;
const int i2;
printf("int       == int,       %s\n", is_compatible(i1,int));
printf("const int == const int, %s\n", is_compatible(i2,const int));
printf("int       == const int, %s\n", is_compatible(i1,const int));
printf("const int == int,       %s\n", is_compatible(i2,int));




ex1.c - one argument generic
ex2.c - two argument generic
ex3.c - check for compatibility




ex3.c - 1KiB - http://archive.main.lv/files/writeup/c_c11_standart__generic_keyword/ex3.c
ex1.c - 1KiB - http://archive.main.lv/files/writeup/c_c11_standart__generic_keyword/ex1.c
ex2.c - 1KiB - http://archive.main.lv/files/writeup/c_c11_standart__generic_keyword/ex2.c
source.tar.gz - 1KiB - http://archive.main.lv/files/writeup/c_c11_standart__generic_keyword/source.tar.gz