Names specified here
Name Description Notes Source Availability
_Alignas Impose stricter alignment L + Keyword C11
_Alignof Compute alignment L + Keyword C11
max_align_t Type with maximum alignment requirement L T <stddef.h> C11
Names specified for <stdalign.h>, “Alignment”
Name Description Notes Source Availability
__alignas_is_defined Indicator of availability of alignas L M <stdalign.h> C11
__alignof_is_defined 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_defined 1
#define __alignof_is_defined 1

max_align_t is a type with the most demanding alignment, so the expression alignof(max_align_t) yields the maximum alignment of any type. max_align_t 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.


CHaR
Sitemap Supported
Site format updated 2024-06-05T22:37:07.391+0000
Data updated 1970-01-01T00:00:00.000+0000
Page updated 2022-06-17T21:43:05.000+0000