C static_assert

Intermediate
6 min read
Updated: Nov 2026
3 examples

What Is static_assert?

A static assertion checks a constant expression at compile time. If the check fails, the program does not build and the compiler prints your message. C11 provides the keyword _Static_assert, and <assert.h> defines the friendlier macro static_assert. It complements the runtime assert() macro.

Remember
#include <assert.h>

static_assert(constant_expression, "message");
_Static_assert(constant_expression, "message");   /* C11 keyword */

true  -> nothing happens, no code generated
false -> compile error showing the message
Featurestatic_assertassert()
CheckedAt compile timeAt run time
ExpressionMust be a constant expressionAny scalar expression
On failureBuild stopsProgram aborts
Cost at run timeNoneA branch (removed with NDEBUG)

How to Use static_assert in C

Put a constant condition and a message wherever a declaration is allowed.

  1. Compile with C11 or newer: gcc file.c -std=c11 -o out.
  2. Include <assert.h> to use the static_assert spelling (or use _Static_assert directly).
  3. Write a condition built from constants, sizeof, offsetof, or CHAR_BIT.
  4. Add a short message that explains what the build assumes.
  5. Place it at file scope, in a struct, or inside a function.
PartRequired?Role
Constant expressionYesEvaluated by the compiler
Message stringC11: yes, C23: optionalShown when the check fails
<assert.h>For the static_assert macro in C11/C17Maps to _Static_assert

Pseudocode

Pseudocode
assumption = some compile-time fact (size, offset, constant)

static_assert(assumption, "why it must hold")

build succeeds only when the assumption is true

Cheat Sheet

Use static assertions to turn silent assumptions into build errors.

TopicDetail
StandardC11 (_Static_assert); C23 makes static_assert a keyword
ConditionInteger constant expression, non-zero means pass
Allowed placesFile scope, block scope, and inside struct declarations
Common checkssizeof, offsetof, CHAR_BIT, enum values
Cannot checkValues known only at run time (use assert)
MessagePlain string literal

Worked Walkthrough — A Failing Check

Consider static_assert(sizeof(int) >= 8, "int must be 64 bits"); on a platform where int is 4 bytes.

Calculation
1) Compiler evaluates sizeof(int)        -> 4
2) Compiler evaluates 4 >= 8              -> 0 (false)
3) Condition is false                     -> diagnostic issued
4) Compilation stops, message is printed

error: static assertion failed: "int must be 64 bits"

No object file is produced, so the bug never reaches run time.

C Examples

Compile with gcc file.c -std=c11 -o out. For run-time checks see assert.h; for layouts see offsetof.

Example 1 — Require a Minimum int Size

Fail the build early if a type is smaller than your code assumes.

C
#include <assert.h>
      #include <stdio.h>
      
      static_assert(sizeof(int) >= 4, "int must be at least 32 bits");
      
      int main(void) {
          printf("sizeof(int) = %zu\n", sizeof(int));
          return 0;
      }

How It Works

  1. File scope. The check lives outside any function.
  2. Constant expression. sizeof(int) >= 4 is known at compile time.
  3. Passes. No code is generated for the assertion.
  4. Program runs. It prints the actual size.

Example 2 — What a Failed Check Looks Like

Change the condition to something false and the build stops with your message.

C
#include <assert.h>
      
      static_assert(sizeof(int) >= 8, "int must be at least 64 bits");
      
      int main(void) {
          return 0;
      }

How It Works

  1. False condition. A 4-byte int is not at least 8 bytes.
  2. Build error. The compiler stops before producing an executable.
  3. Message shown. Your text explains the broken assumption.
  4. Wording varies. Exact diagnostics differ between GCC, Clang, and MSVC.

Example 3 — Guard a Struct Layout with offsetof

Lock in the layout of a struct that is shared with other code or files.

C
#include <assert.h>
      #include <stddef.h>
      #include <stdint.h>
      #include <stdio.h>
      
      struct Packet {
          uint16_t id;
          uint16_t len;
          uint8_t payload[8];
      };
      
      static_assert(offsetof(struct Packet, payload) == 4,
                    "payload must start at byte 4");
      static_assert(sizeof(struct Packet) == 12,
                    "Packet must be 12 bytes");
      
      int main(void) {
          printf("sizeof(struct Packet) = %zu\n", sizeof(struct Packet));
          return 0;
      }

How It Works

  1. Layout. Two 16-bit fields (4 bytes) then 8 payload bytes, with no padding on common ABIs.
  2. offsetof is constant. It can be used inside a static assertion.
  3. Future-proof. Reordering fields or adding a larger member breaks the build instead of the protocol.
  4. Related. See Structures for padding rules.

Edge Cases & Pitfalls

Static assertions are simple, but a few rules trip people up.

constant

Condition must be constant

A variable or function result is rejected. Use assert() for run-time values.

standard

Needs C11 or later

Older compilers (C99 and earlier) lack it. Compile with -std=c11 or newer.

include

Forgetting assert.h

Without <assert.h> in C11/C17, static_assert is undefined. _Static_assert still works.

message

Missing message in C11

C11 requires the message string. C23 makes it optional.

compat

Used in headers

Static assertions are safe to put in headers; they add no run-time code.

Performance Notes

AspectCostNotes
Run timeNoneNothing is generated
Compile timeNegligibleOne constant evaluation
FailureBuild errorCaught before shipping

Prefer static assertions over comments for assumptions about type sizes, struct layouts, and enum ranges. They cost nothing at run time and cannot go stale silently.

Key Takeaways

  • Timing: checked at compile time, with no run-time cost.
  • Syntax: static_assert(cond, "msg"); or _Static_assert.
  • Input: the condition must be a constant expression.
  • Use: guard sizes, offsets, and platform assumptions.

One line: turn assumptions into build errors with static_assert.

Frequently Asked Questions

A compile-time check introduced in C11 as _Static_assert. The assert.h header provides the static_assert macro. If the constant condition is false, compilation fails.
assert() runs while the program executes and can use any value. static_assert is evaluated by the compiler and needs a constant expression.
For the static_assert spelling in C11 and C17, yes. In C23 static_assert is a keyword. _Static_assert needs no header.
No. It generates no code, so the compiled program is unchanged.
Yes. Both are constant expressions, so they are ideal for checking sizes and struct layouts.
In C11 and C17, yes. C23 allows omitting the message.

Next: UTF-8 in C

Handle multi-byte text safely in C strings.

UTF-8 in C tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful