r/C_Programming • u/nocitus • Mar 24 '22
Discussion Do you use _Generic? If so, why?
I just want to know what other C devs think of _Generic. I use it sparingly, if ever. Do you think it was a good addition to the C standard?
8
Upvotes
13
u/beej71 Mar 24 '22
As for whether or not it was a "good" addition...
I have to admit I wince a little with almost every addition to the standard. Remember how much simpler everything used to be!
Do we need it? No. (Really we just need NAND, right?)
But it does have the advantage of attacking the combinatorial explosion of function names in the library. Maybe that'll help in the future as even more things are added.
Also it's a compile-time mechanism with no run-time overhead, so I'm more friendly to it than I am toward things like VLAs.
4
u/jacksaccountonreddit Mar 25 '22
I'm using it in a container library to support multiple hash table key types with one interface and without the performance hit of function pointers. The user can even add their own key types. I described how we can create a user-extendable _Generic macro yesterday in a response to a Stack Overflow question.
7
u/wsppan Mar 24 '22
think of it as a switch statement for types
http://www.robertgamble.net/2012/01/c11-generic-selections.html?m=1
1
u/Taxerap Mar 24 '22
I use it mainly to get rid of format strings, since format strings are great sources of exploits.
1
u/beej71 Mar 24 '22
<tgmath.h>certainly uses it extensively, and I could see being inspired by that to use similar patterns in my libraries.But to answer the question, no I haven't used it. 🙂
1
u/UltraLowDef Mar 25 '22
i use it quite a bit in libraries to make code calls more uniform and less error prone (calling a function for unsigned instead of signed or short instead of long).
0
u/[deleted] Mar 24 '22
[deleted] — view deleted comment
-1
u/[deleted] Mar 24 '22
[removed] — view removed comment