tech-kern archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]
Re: Do all -current compilers support C23 typed enum syntax?
On Dec 3, 2026, at 7:07 PM, Taylor R Campbell <riastradh%NetBSD.org@localhost> wrote:
>
> The compiler, being very clever, sees that all enumerated values of
> enum cmd have been covered by the switch, so it helpfully deletes some
> code it can _prove_ is dead -- this part:
>
> default:
> panic("unknown command”);
This is a really interesting observation! In Swift you have to explicitly mark the default case as supporting an unknown value to avoid such an optimization; it wouldn’t surprise me if the C-family compiler folks at Apple initially avoided such an optimization because of the risks.
However, it looks like sometime in the last couple years Apple has also decided they want to support the optimization you describe: clang now has additional __attribute__(()) magic for telling the compiler how to handle this case more explicitly, by indicating whether an enum should be treated as open or closed:
#if __has_attribute(enum_extensibility)
#define __CF_ENUM_ATTRIBUTES __attribute__((enum_extensibility(open)))
#define __CF_CLOSED_ENUM_ATTRIBUTES __attribute__((enum_extensibility(closed)))
#define __CF_OPTIONS_ATTRIBUTES __attribute__((flag_enum,enum_extensibility(open)))
// ...
#endif
Then in the definition of the wrapper macros they stick the appropriate ATTRIBUTES macro in the right place for the definition. However, I have no idea whether any other compiler (like, oh, GCC!) understands these attributes though, and it looks like they were added at least in part to improve the ergonomics of importing C APIs to Swift rather than to improve C ergonomics: <https://www.swift.org/blog/improving-usability-of-c-libraries-in-swift/>
(The “flag_enum” stuff is an enum used to define bit flags which may be combined -- another common use for C enums which may have caused the compiler to avoid such optimizations in the past.)
-- Chris
Home |
Main Index |
Thread Index |
Old Index