Workarounds for C11 _Generic
a day ago
- C11's _Generic allows compile-time type-based selection but requires all unselected branches to be semantically valid, limiting its usefulness.
- The main bug is that unselected output expressions must compile without errors, preventing direct use of type-specific operations like field access.
- A workaround is to select only function names inside _Generic and apply arguments afterward, as done in <tgmath.h>.
- When function selection isn't possible, type coercion via nested _Generic with dummy values can maintain semantic validity.
- For multi-type switches, combining types into arrays via type IDs or function pointer types provides a workaround.
- Chaining _Generic with default clauses handles conflicts between standard and typedef integer types.
- Complex workarounds lead to poor error messages with opaque types and exponential macro expansion, potentially causing slow compilation or crashes.
- Despite limitations, _Generic is useful for deliberate compile-time error checking during refactoring (e.g., blocking incorrect free calls).