惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
Scott Helme
Scott Helme
Know Your Adversary
Know Your Adversary
NISL@THU
NISL@THU
C
Cyber Attacks, Cyber Crime and Cyber Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Schneier on Security
I
Intezer
Spread Privacy
Spread Privacy
AWS News Blog
AWS News Blog
V
Vulnerabilities – Threatpost
Cloudbric
Cloudbric
V2EX - 技术
V2EX - 技术
Google Online Security Blog
Google Online Security Blog
L
Lohrmann on Cybersecurity
Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
LINUX DO - 热门话题
S
Secure Thoughts
T
The Exploit Database - CXSecurity.com
博客园 - 【当耐特】
Recent Announcements
Recent Announcements
Security Archives - TechRepublic
Security Archives - TechRepublic
Stack Overflow Blog
Stack Overflow Blog
罗磊的独立博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
K
Kaspersky official blog
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
Latest news
Latest news
B
Blog
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
L
LangChain Blog
GbyAI
GbyAI
Last Week in AI
Last Week in AI
S
Security Affairs
Apple Machine Learning Research
Apple Machine Learning Research
N
Netflix TechBlog - Medium
Security Latest
Security Latest
Vercel News
Vercel News
Y
Y Combinator Blog
G
GRAHAM CLULEY
S
Securelist
T
Troy Hunt's Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
雷峰网
雷峰网

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Enum Type Safety in C
JP Hutchins · 2026-06-22 · via DEV Community

The C standard allows the programmer to define new types, including enumerated types—or "enums"—that improve program readability and type safety. This article explores the specification for enumerated types, the compiler options that improve enum type safety, and why type safety prevents run time errors. The focus is on the GCC and Clang C compilers targeting ARM32 (e.g. Cortex-M MCUs), but the same conclusions should apply to all C targets, including RISCV, x86_64, and ARM64.

Table of Contents

C Enums

C enums enable the definition of new types that are collections of symbols. Each symbol is mapped to an integer value. The integer value may be arbitrary or it may be a useful part of the representation.

For example, an enumeration of colors might look like this:

enum color {
    COLOR_RED = 0,
    COLOR_GREEN = 1,
    COLOR_BLUE = 2,
};

The value of 0 being given to red, 1 to green, and 2 to blue is arbitrary—the values used could be any set of three numbers. Because the use of unique integers with arbitrary values is so common, an enum member definition that does not include the value will automatically be assigned the preceding value plus one:

enum color {
    COLOR_RED = 0,
    COLOR_GREEN,  // automatically 1
    COLOR_BLUE,  // automatically 2
};

This is simpler, and in the case where new symbols may appear anywhere in the definition, it is preferred, because it will prevent accidental creation of shared values when unique values are required.

On the other hand, an enumeration of speed limits may map to constant integer values that are useful and not-at-all arbitrary:

enum speed_limit {
    SPEED_LIMIT_30_KPH = 30,
    SPEED_LIMIT_60_KPH = 60
    SPEED_LIMIT_90_KPH = 90,
};

Lastly, the enumerated values do not need to be unique. Multiple symbols can map to the same literal integer, though the intent is often more clear by mapping to the symbol rather than the literal integer:

enum font {
    FONT_TIMES_NEW_ROMAN = 0,
    FONT_HELVETICA,
    FONT_DEFAULT = FONT_HELVETICA,  // instead of 1
};

All of the examples "namespace" the enum by prefixing members with the name of the type—the name of the collection—as is common practice in C because the type itself cannot be used as the namespace. That is, it's not possible to use enum color::RED. Don't dismay! More sophisticated strategies to enforce type safety are the subject of this very article.

The C Standard

The C standard states that enumerated types (enums) that are defined by the programmer are unique types.

In the draft version (ISO/IEC 9899:2024 (en) — N3220) of C23, we find a definition for C enumerations:

An enumeration comprises a set of named integer constant values. Each distinct enumeration
constitutes a different enumerated type.
N3220, 6.2.5 Types (p. 40)

It's important to note that C23 enables specifying the underlying type of the enumeration, which is a very good idea.

An identifier declared as an enumeration constant for an enumeration without a fixed underlying
type has either type int or the enumerated type, as defined in 6․7.3.3. An identifier declared
as an enumeration constant for an enumeration with a fixed underlying type has the associated
enumerated type.
N3220, 6․4․4․4 Enumeration constants (p. 63)

The definition of "enumerated type" from section *6․7.3.3 Enumeration specifiers * (p. 109):

2 All enumerations have an underlying type. The underlying type can be explicitly specified using an
enum type specifier and is its fixed underlying type. If it is not explicitly specified, the underlying
type is the enumeration’s compatible type, which is either char or a standard or extended signed or
unsigned integer type.
N3220, 6․7.3.3 Enumeration specifiers (p. 109)

So actually, it's probably int, or maybe not, because it's implementation-defined (i.e. up to the authors of GCC, Clang, etc.):

13 For all enumerations without a fixed underlying type, each enumerated type shall be compatible
with char or a signed or an unsigned integer type that is not bool or a bit-precise integer type. The
choice of type is implementation-defined but shall be capable of representing the values of all
the members of the enumeration.
N3220, 6․7.3.3 Enumeration specifiers (p. 109)

The behavior is muddied further with compiler options like -fshort-enums that will use the smallest possible integer representation for the enumeration's underlying type.

Fixed Underlying Type

Fortunately, there is no (good) reason to use -fshort-enums since C23 allows specifying a fixed underlying type for each enumerated type definition:

#include <stdint.h>

enum eight_bit : uint8_t {
    HEX00 = 0x00,
    HEX01 = 0x01,
};

And, because it's in the C standard, compilers must generate an error if one of the enumeration constants doesn't fit in the fixed underlying type:

#include <stdint.h>

enum eight_bit : uint8_t {
    HEX100 = 0x100
};

GCC 14.2.0 (unknown-eabi):

<source>:4:14: error: enumerator value outside the range of underlying type
    8 |  HEX100 = 0x100,
      |  ^~~~~
Compiler returned: 1

Type Safety

Because C enums are types, they should afford some degree of type safety. Type safety provides compile time assurances that improve program expressiveness, correctness, size, and performance. However, compilers do not provide type safety for C enums by default.

The following examples were tested with two compilers: ARM GCC 14.2.0 (unknown-eabi) and armv7-a clang 18.1.0. The compiler and program output is the same between the two compilers unless otherwise noted.

Exhaustiveness

Generally, when an enum is used in a switch statement, the intention is that all constants of the enumerated type are matched by a case. If that's not the intention, then it's likely that the enum type should be constrained to a more narrow collection of constants. When the matching handles every possible case, it is said to be exhaustive.

Here's an example with a runtime error lurking—because the switch is not exhaustive, it is possible to hit the assert(0) after the switch!

Interact with this example on Compiler Explorer

#include <assert.h>
#include <stdint.h>
#include <stdio.h>

enum event : uint8_t {
    EVENT_A = 0,
    EVENT_B,
};

enum result : uint8_t {
    RESULT_A = 0,
    RESULT_B,
};

enum result handle_event(enum event event) {
    switch (event) {
        case EVENT_A:
            return RESULT_A;
    }
    assert(0);
}

int main(void) {
    enum result result = handle_event(0);

    printf("%d\n", result);
}

Compiler options: -Werror:

Compiler returned: 0

Program output:

Program returned: 0
Program stdout
0

The handle_event() function implies that it can handle all members of enum event. In reality, the programmer has failed to match the EVENT_B case, so passing EVENT_B, or 1, as the function argument will cause a runtime error:

int main(void) {
    enum result result = handle_event(1);

    printf("%d\n", result);
}

Compiler options: -Werror:

Compiler returned: 0

Program output:

Program returned: 139
Program stderr
output.s: /app/example.c:20: handle_event: Assertion `0' failed.
Program terminated with signal: SIGSEGV

Fortunately, simply adding -Wall covers this common mistake (-Wextra is added for completeness).

GCC -Werror -Wall -Wextra:

<source>: In function 'handle_event':
<source>:16:5: error: enumeration value 'EVENT_B' not handled in switch [-Werror=switch]
   16 |  switch (event) {
      |  ^~~~~~
cc1: all warnings being treated as errors
Compiler returned: 1

Clang -Werror -Wall -Wextra:

<source>:16:13: error: enumeration value 'EVENT_B' not handled in switch [-Werror,-Wswitch]
   16 |  switch (event) {
      | ^~~~~
1 error generated.
Compiler returned: 1

Importantly, we can reintroduce this runtime bug by adding a default: case:

enum result handle_event(enum event event) {
    switch (event) {
        case EVENT_A:
            return RESULT_A;
        default:
            assert(0);
    }
}

Compiler options -Werror -Wall -Wextra:

Compiler returned: 0

The conclusion is that the use of a default: case in the switch statement is counterproductive to type safety.

Type Checking

By adding -Wall and avoiding use of a default: case, the switch statement over the enum event is exhaustive, therefore it is impossible for a runtime error to occur when the argument given to handle_event() is guaranteed to be an enum event. However, because the GCC and Clang compilers do not strictly check the type given to handle_event(), the program remains vulnerable to other run time errors.

In this example, 2 is passed to handle_event() without generating a compile time error. At run time, it is found that 2 is not handled by the switch, causing the assertion to be hit.

Interact with this example on Compiler Explorer

#include <assert.h>
#include <stdint.h>
#include <stdio.h>

enum event : uint8_t {
    EVENT_A = 0,
    EVENT_B,
};

enum result : uint8_t {
    RESULT_A = 0,
    RESULT_B,
};

enum result handle_event(enum event event) {
    switch (event) {
        case EVENT_A:
            return RESULT_A;
        case EVENT_B:
            return RESULT_B;
    }
    assert(0);
}

int main(void) {
    enum result result = handle_event(2);

    printf("%d\n", result);
}

Compiler options: -Werror -Wall -Wextra:

Compiler returned: 0

Program output:

Program returned: 139
Program stderr
output.s: /app/example.c:22: handle_event: Assertion `0' failed.
Program terminated with signal: SIGSEGV

-Wextra has added -Wenum-conversion, but it doesn't quite do what we want:

Warn when a value of enumerated type is implicitly converted to a different enumerated type. This warning is enabled by -Wextra in C.
GNU.org

-Wenum-conversion will generate a warning if we provide an incompatible enum as argument, even though both the underlying type and value are the same:

    enum result result = handle_event(RESULT_A);

GCC -Werror -Wall -Wextra:

<source>:26:39: error: implicit conversion from 'enum result' to 'enum event' [-Werror=enum-conversion]
   26 |  enum result result = handle_event(RESULT_A);
      |   ^~~~~~~~

Instead, what we're looking for is an error caused by passing the underlying type—the integer literal 2, in the example—instead of the enumerated type as argument. It is provided by -Wall in the form of Wenum-int-mismatch, but there is a catch in the fine print:

Warn about mismatches between an enumerated type and an integer type in declarations...

...In C, an enumerated type is compatible with char, a signed integer type, or an unsigned integer type. However, since the choice of the underlying type of an enumerated type is implementation-defined, such mismatches may cause portability issues. In C++, such mismatches are an error. In C, this warning is enabled by -Wall and -Wc++-compat.
GNU.org

So, in GCC, we need -Wc++-compat for the desired compile time type safety.

GCC -Werror -Wall -Wextra -Wc++-compat:

<source>:26:39: error: enum conversion when passing argument 1 of 'handle_event' is invalid in C++ [-Werror=c++-compat]
   26 |  enum result result = handle_event(2);
      |   ^
<source>:15:13: note: expected 'enum event' but argument is of type 'int'
   15 | enum result handle_event(enum event event) {
      | ^~~~~~~~~~~~

Clang's -Wassign-enum prevents an error when the integer literal is out of bounds, but it does not cover the general case of enforcing usage of the enum type rather than the underlying type.

Clang -Werror -Wall -Wextra -Wassign-enum:

source>:26:39: error: integer constant not in range of enumerated type 'enum event' [-Werror,-Wassign-enum]
   26 |  enum result result = handle_event(2);
      |   ^

If you know of a Clang compiler option that can enforce this, let me know in the comments! One way to improve things is to use the C++ compiler instead of the C compiler.

Clang C++ armv7-a clang 18.1.0 (no options needed):

<source>:26:26: error: no matching function for call to 'handle_event'
   26 |  enum result result = handle_event(1);
      |  ^~~~~~~~~~~~
<source>:15:13: note: candidate function not viable: no known conversion from 'int' to 'enum event' for 1st argument
   15 | enum result handle_event(enum event event) {
      | ^        ~~~~~~~~~~~~~~~~

Even though the integer literal is in range of the enum, use of the integer literal still causes a compile time error as desired.

[!TIP] Casting

Of course it is possible to cast any random value to the enum type and reintroduce the run time error. Why would a programmer do this? This is a non-issue when the use of casts is avoided altogether—a topic for another article.

If an enum value is not known at compile time (e.g. it's from the user or received on a transport), then the programmer should write a validation function or macro for use when assigning these "unknown values" to the enum type.

Conclusion

While the C standard may not provide guarantees about enum type safety, the specification lays the groundwork on which compilers have built meaningful assurances of run time correctness.

By avoiding use of a default case and adding the -Werror -Wall -Wextra -Wc++-compat compiler options, it is "impossible to generate a run time error". Yet, if that is true, then it raises a question about
the necessity of runtime type checking.

[!CAUTION]

If a run time error is not possible, can assert(0) be replaced with __builtin_unreachable()?

enum result handle_event(enum event event) {
    switch (event) {
        case EVENT_A:
            return RESULT_A;
        case EVENT_B:
            return RESULT_B;
    }
    __builtin_unreachable();
}

It certainly compiles and results in smaller code size. But, without the set of compiler options -Werror -Wall -Wextra -Wc++-compat, this is precariously vulnerable to undefined behavior:

If control flow reaches the point of the __builtin_unreachable, the program is undefined.
GNU.org

I cannot answer this question confidently, but I can say that I will continue to use defensive runtime assertions and/or error code returns instead of __builtin_unreachable(). The benefits of compile time type safety are not solely found in code size and efficiency, but also in the labor that is saved by preventing run time errors.

You can fiddle with the final type safe example at Compiler Explorer.