Hacker News new | ask | show | jobs
by paxcoder 3446 days ago
Unfortunately __typeof__ is non-standard. Despite its usefulness it always gets left out of the standard (and with weird excuses, I think last time it was lack of implementations - despite the fact that eg. both GCC and LLVM implement it).

Interestingly, C11 defines _Generic selection, a kind of a switch for types, but its usefulness is hindered by the fact that it cannot be used in conjunction with sizeof.

1 comments

Expression macros `({, })` aren't standard either. But I sort of go with, if all gcc/clang/tinycc support it and it's a highly useful feature, then it's part of C as far as I'm concerned. It would certainly be nice if ({,}),__typeof__, and __label__ became part of the C standard, though.
My Google skills are failing me here. Is `({,})` a special construct, or are the '{' and '}' metacharacters and you're just referring to variadic macros, which are standard as of C11?
It's a common (gcc/clang/tcc) compiler extension (chapter 6.1 of the gcc manual) that allows you to use parentheses around a compound statement to turn the compound statement into an expression whose value is the last statement in the compound statement. For example `({ int _r; if((_r=foo())) bar(); _r })` behaves like an inline function that returns `_r`. If you want to do generic vector ops purely with macros and you want to do it robustly, you effectively need for the macros to "return" a value signalling whether the potential realloc that might have happened inside the macro succeeded or not. It's a very powerful feature because it allows you to have macros that behave like ducktyped, value-returning inline functions. (Sometimes you'll need to tone down the ducktyping a little, like it's probably a good idea to use some __typeof__-based typechecks (http://stackoverflow.com/questions/41250083/typechecking-in-...) to make the compiler warn you if you attempt to memcpy doubles into an int vector from your vector__insert method.)
Thank you! I've never seen this before; looks handy.