1static_assert(3) Library Functions Manual static_assert(3)
2
3
4
6 static_assert, _Static_assert - fail compilation if assertion is false
7
9 Standard C library (libc)
10
12 #include <assert.h>
13
14 void static_assert(scalar constant-expression, const char *msg);
15
16 /* Since C23: */
17 void static_assert(scalar constant-expression);
18
20 This macro is similar to assert(3), but it works at compile time, gen‐
21 erating a compilation error (with an optional message) when the input
22 is false (i.e., compares equal to zero).
23
24 If the input is nonzero, no code is emitted.
25
26 msg must be a string literal. Since C23, this argument is optional.
27
28 There's a keyword, _Static_assert(), that behaves identically, and can
29 be used without including <assert.h>.
30
32 No value is returned.
33
35 In C11, the second argument (msg) was mandatory; since C23, it can be
36 omitted.
37
39 C11 and later.
40
42 static_assert() can't be used in some places, like for example at
43 global scope. For that, a macro must_be() can be written in terms of
44 static_assert(). The following program uses the macro to get the size
45 of an array safely.
46
47 #include <assert.h>
48 #include <stddef.h>
49 #include <stdint.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53
54 /*
55 * This macro behaves like static_assert(), failing to
56 * compile if its argument is not true. However, it always
57 * returns 0, which allows using it everywhere an expression
58 * can be used.
59 */
60 #define must_be(e) \
61 ( \
62 0 * (int) sizeof( \
63 struct { \
64 static_assert(e); \
65 int ISO_C_forbids_a_struct_with_no_members; \
66 } \
67 ) \
68 )
69
70 #define is_same_type(a, b) \
71 __builtin_types_compatible_p(typeof(a), typeof(b))
72
73 #define is_array(arr) (!is_same_type((arr), &*(arr)))
74 #define must_be_array(arr) must_be(is_array(arr))
75
76 #define sizeof_array(arr) (sizeof(arr) + must_be_array(arr))
77 #define nitems(arr) (sizeof((arr)) / sizeof((arr)[0]) \
78 + must_be_array(arr))
79
80 int foo[10];
81 int8_t bar[sizeof_array(foo)];
82
83 int
84 main(void)
85 {
86 for (size_t i = 0; i < nitems(foo); i++) {
87 foo[i] = i;
88 }
89
90 memcpy(bar, foo, sizeof_array(bar));
91
92 for (size_t i = 0; i < nitems(bar); i++) {
93 printf("%d,", bar[i]);
94 }
95
96 exit(EXIT_SUCCESS);
97 }
98
100 assert(3)
101
102
103
104Linux man-pages 6.04 2023-01-26 static_assert(3)