August 4th, 2024

Improving _Generic in C2y

The C programming community is enhancing the _Generic feature for the C2y standard to resolve issues from C23, focusing on simplifying type matching and addressing limitations in usability and behavior.

Read original articleLink Icon
Improving _Generic in C2y

The C programming community is currently working on improvements to the _Generic feature as part of the C2y standard, following the completion of C23. The aim is to address issues that arose during previous standardization cycles, particularly the long delays between bug fixes and releases that hindered contributions. _Generic, introduced in C11, allows for type-based behavior by matching expressions to types, but it has faced criticism for its complexity and limitations, particularly regarding l-value conversion, which can strip qualifiers from types.

Two main problems with _Generic have been identified: the need for l-value conversion complicates type matching, and the feature only accepts expressions, which limits its usability. To address these issues, a proposal (N3260) was introduced to allow type names in place of expressions, enabling direct type matching without the complications of l-value conversion. This change has been implemented in Clang and is expected to be adopted by GCC.

While the new implementation simplifies the use of _Generic, it may introduce confusion in certain scenarios, particularly regarding type matching with expressions. Further refinements are anticipated to enhance compatibility and address undefined behaviors associated with variable-length arrays. Overall, these developments represent a significant step forward in improving the usability and functionality of _Generic in C programming.

Link Icon 4 comments
By @fanf2 - 2 months
The article describes two problems with _Generic.

There is a third: the discarded branches must typecheck. (Unlike C++ templates, where substitution failure is not an error.) Simon Tatham described the issue in more detail:

https://www.chiark.greenend.org.uk/~sgtatham/quasiblog/c11-g...

By @colonwqbang - 2 months
Nice, does this mean we can have const-generic accesors now? I.e. &s->somefield and get a const pointer if s was a const pointer, but a mutable one otherwise? I guess we still need to define two functions though, but that can probably be handled by macros. This is something that really hinders use of const in current C.
By @Conscat - 2 months
Clang, as a non-standard feature, allows you to put a type-id into `_Generic` rather than an expression.
By @brcmthrowaway - 2 months
Wow, I can't believe they wasted a decade on 2 releases

Move fast!