Name | Description | Notes | Source | Availability | |||||||
---|---|---|---|---|---|---|---|---|---|---|---|
_Alignas |
Impose stricter alignment | L | + | Keyword | C11 | ||||||
_Alignof |
Compute alignment | L | + | Keyword | C11 | ||||||
max_ |
Type with maximum alignment requirement | L | T | <stddef.h> |
C11 |
Name | Description | Notes | Source | Availability | |||||||
---|---|---|---|---|---|---|---|---|---|---|---|
__alignas_ |
Indicator of availability of alignas |
L | M | <stdalign.h> |
C11 | ||||||
__alignof_ |
Indicator of availability of alignof |
L | M | <stdalign.h> |
C11 | ||||||
alignas |
Impose stricter alignment | L | M | + | <stdalign.h> |
C11 | |||||
alignof |
Compute alignment | L | M | + | <stdalign.h> |
C11 |
This header is available in C11.
All complete types in C have alignment requirements. The alignment of a type is the minimum number of bytes between two unequal addresses that are valid for that type. If you have a valid address for a pointer to some type, you can add or subtract multiples of the type's alignment and obtain other valid addresses (subject to range constraints). All alignments are positive integral powers of two, i.e., 1, 2, 4, 8, etc. An implementation also has a maximum alignment.
From C11, you can obtain the
alignment as a size_t
with an expression such
as:
_Alignof(int)
- unary-expression
_Alignof ( type-name )
- declaration-specifiers
alignment-specifier declaration-specifiersopt
- alignment-specifier
_Alignas ( type-name )
_Alignas ( constant-expression )
An alignment constraint can be applied to an object declaration:
_Alignas(struct tm) char block[100];
_Alignas
can take either a type or an integer expression. The integer
value is the constraint, and if a type is passed, it
is converted to a constraint as if by _Alignof(type)
.
The header <stdalign.h>
defines
several macros relating to alignment:
#define alignas _Alignas #define alignof _Alignof #define __alignas_is_ 1 #define __alignof_defined is_ 1defined
max_
is a type with the most demanding alignment, so the
expression alignof(max_
yields the maximum alignment of any type. max_
is defined in <stddef.h>
.
Prior to C11, you can use this technique to achieve alignment:
There's an error here.
#define Tchar(T) struct { T t; char c; } #define strideof(T) \ (sizeof(Tchar(T)) > sizeof(T) ? \ sizeof(Tchar(T)) - sizeof(T) : sizeof(T)) #define align(S,T) \ (((S) + (strideof(T) - 1u)) / strideof(T) * strideof(T))
strideof(T)
should give the
alignment of type T
, or something
stricter. If S
is an offset from an
address aligned for all types, such as that returned by
malloc
, then align(S, T)
should yield the next valid offset
after S
that is correctly aligned for
type T
.