CodeBlanks Logo Icon CodeBlanks

_Static_assert

Learn compile-time checks with _Static_assert.

_Static_assert compile-time check

_Static_assert is a compile-time check introduced in C11. It is written as _Static_assert(constant_expr, "message");. If the constant expression is false (zero), compilation stops and the message is shown.

This is used to verify conditions known at compile time, such as struct sizes, constant values and type traits. Including <assert.h> gives you the static_assert alias. Unlike the run-time assert, _Static_assert has no run-time cost; the check happens entirely during compilation.

Using _Static_assert

A typical use is checking struct size or constant values. _Static_assert(sizeof(int) >= 4, "int at least 4 bytes"); verifies that int is at least 4 bytes. If a platform has a smaller int, compilation stops.

This is a powerful tool for portability checks. It is used in header files to document and verify platform assumptions. The message appears in the compiler error, helping another developer understand why compilation stopped. _Static_assert is also used for enum value ranges and compile-time constants.

Practice Add _Static_assert and print

Add _Static_assert(sizeof(int) >= 4, "int en az 4 bayt");. Write int main(void) and inside it print printf("Denetim geçti\n");.

Starter code

main.c
#include <stdio.h>

// derleme zamanı denetimi ekle
// main'de "Denetim geçti" yazdır

Sample solution

main.c
#include <stdio.h>

_Static_assert(sizeof(int) >= 4, "int en az 4 bayt");

int main(void) {
    printf("Denetim geçti\n");
    return 0;
}

Expected output

Denetim geçti

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match check types

Term Meaning
_Static_assert Compile time
assert Run time
#if Preprocessor
if Flow control

2 Complete the _Static_assert condition

Question
_Static_assert(sizeof(int) >= ____, "int en az 4 bayt");
Answer
_Static_assert(sizeof(int) >= 4, "int en az 4 bayt");

Explanation: int must be at least 4 bytes; this is a common portability assumption.

3 When does _Static_assert fire?

  • At run time, if the condition is false
  • At link time, if a symbol is missing
  • At compile time, if the condition is false Correct answer
  • At load time, if addresses collide

Explanation: _Static_assert runs at compile time; if the condition is false, compilation stops.

All lessons in Expert