Debian Codegraph @

upstream/debian-unstable/man3/static_assert.3

raw
1 .\" Copyright, the authors of the Linux man-pages project
2 .\"
3 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
4 .\"
5 .TH static_assert 3 2026-04-20 "Linux man-pages 6.18"
6 .SH NAME
7 static_assert, _Static_assert \- fail compilation if assertion is false
8 .SH LIBRARY
9 Standard C library
10 .RI ( libc )
11 .SH SYNOPSIS
12 .nf
13 .B #include <assert.h>
14 .P
15 .BI "void static_assert(bool " constant-expression ", const char *" msg );
16 .P
17 /* Since C23: */
18 .BI "void static_assert(bool " constant-expression );
19 .fi
20 .SH DESCRIPTION
21 This macro is similar to
22 .BR \%assert (3),
23 but it works at compile time,
24 generating a compilation error (with an optional message)
25 when the input is false (i.e., compares equal to zero).
26 .P
27 If the input is nonzero,
28 no code is emitted.
29 .P
30 .I msg
31 must be a string literal.
32 Since C23, this argument is optional.
33 .P
34 There's a keyword,
35 .BR \%_Static_assert (),
36 that behaves identically,
37 and can be used without including
38 .IR <assert.h> .
39 .SH RETURN VALUE
40 No value is returned.
41 .SH STANDARDS
42 C23.
43 .SH HISTORY
44 C11.
45 .P
46 In C11,
47 the second argument
48 .RI ( msg )
49 was mandatory;
50 since C23,
51 it can be omitted.
52 .SH EXAMPLES
53 .BR static_assert ()
54 can't be used in some places,
55 like for example at global scope.
56 For that,
57 a macro
58 .BR \%must_be ()
59 can be written in terms of
60 .BR \%static_assert ().
61 The following program uses the macro to get the size of an array safely.
62 .P
63 .in +4n
64 .\" SRC BEGIN (must_be.c)
65 .EX
66 #include <assert.h>
67 #include <stdint.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 \&
72 /*
73 * This macro behaves like static_assert(), failing to
74 * compile if its argument is not true. However, it always
75 * returns 0, which allows using it everywhere an expression
76 * can be used.
77 */
78 #define must_be(e) \[rs]
79 ( \[rs]
80 0 * (int) sizeof( \[rs]
81 struct { \[rs]
82 static_assert(e); \[rs]
83 int ISO_C_forbids_a_struct_with_no_members; \[rs]
84 } \[rs]
85 ) \[rs]
86 )
87 \&
88 #define is_same_type(a, b) \[rs]
89 __builtin_types_compatible_p(typeof(a), typeof(b))
90 \&
91 #define is_array(arr) (!is_same_type((arr), &*(arr)))
92 #define must_be_array(arr) must_be(is_array(arr))
93 \&
94 #define sizeof_array(arr) (sizeof(arr) + must_be_array(arr))
95 #define NITEMS(arr) (sizeof((arr)) / sizeof((arr)[0]) \[rs]
96 + must_be_array(arr))
97 \&
98 int foo[10];
99 int8_t bar[sizeof_array(foo)];
100 \&
101 int
102 main(void)
103 {
104 for (size_t i = 0; i < NITEMS(foo); i++) {
105 foo[i] = i;
106 }
107 \&
108 memcpy(bar, foo, sizeof_array(bar));
109 \&
110 for (size_t i = 0; i < NITEMS(bar); i++) {
111 printf("%d,", bar[i]);
112 }
113 \&
114 exit(EXIT_SUCCESS);
115 }
116 .EE
117 .\" SRC END
118 .in
119 .SH SEE ALSO
120 .BR assert (3)