3 ms·
Note that C11 added _Generic to the language, so things like the type-generic functions from tgmath.h can nowadays be implemented in user space.
by cygx 5y ago
Note that C11 added _Generic to the language, so things like the type-generic functions from tgmath.h can nowadays be implemented in user space.
- an1sotropy 5y agoIndeed; thanks. I do appreciate knowing that <tgmath.h> does this for all the math functions in one fell swoop. speaking of FP-precision genericity, I really wish there was a format specification for printf that would reliably print a floating-point number with just enough digits to recover the bits of the given value (float or double), but the given value will already have been promoted to double since printf is variadic.
- belgesel 5y agoAlthough I disagree with some part of the presenter's ideas. I learned struct initializers and _Generic keyword from the presentation. So that is a great win for me. Now I can write safer code with the const and non-const pointer types. Suppose that I want to return a pointer to a field inside of a struct. Either I had to write const and non-const versions of the same function and use them which brings unreadable code. Or I would have to define argument as const and return non-const pointer which defeats the purpose of const in the first place. This keyword allows me to use same function name with const and non-const pointers.
- an1sotropy 5y agoI just noticed your comment and I'm intrigued. Can you explain more or give a tiny example of this const/non-const flexibility?
- belgesel 5y agoSuppose I have the following struct and functions. struct my_struct{int a; char private[10];} void * get_struct_field_nonconst(struct my_struct *ptr) { return &(ptr->private[0]); } With these elements you are only allowed to give non-const pointers to read or write inside private field. In order to truly apply this to const pointers (no casting etc.) you will need another get_struct_field() function but defined as this. const void * get_struct_field_const(const struct my_struct *ptr) { return &(ptr->private[0]); } This will work but it is ugly. Here _Generic keyword allows you to write these functions but use them with a common name. Such as get_struct_field(). And that would be something like this: #define get_struct_field(ptr) \ _Generic((ptr), \ const struct my_struct * : get_struct_field_const, \ struct my_struct * : get_struct_field_nonconst) \ (ptr) Hope this would help!
- an1sotropy 5y ago(slow answer) yes, thanks for the example!)