liveBook · Manning

Alignas

As explained in Modern C

alignas, also spelled _Alignas, is a C11 alignment specifier that requests a specified alignment for an object or member.

alignas, also spelled _Alignas, is the C11 alignment specifier. It requests a specified alignment for an object or structure member; the argument may be a type or an expression. section 12.7

Requesting useful alignments

alignas(sizeof(complex double)) complex double z; alignas(sizeof(float[4])) float fvec[4]; These declarations request alignment suited to a complex value and a four-element float array. Similar syntax can align a byte array to the requirements of unsigned: alignas(unsigned) unsigned char A[sizeof(unsigned)] = { 9 }; section 12.7

TAKEAWAYS

  • Use alignas when a platform can perform an operation more efficiently with data positioned at a chosen alignment, including on cache boundaries. section 12.7 section 15.0
  • Do not treat alignment as a remedy for the Effective Type Rule; aligned storage can still be used invalidly. section 12.7
  • Remember that alignas and alignof serve different roles: alignas requests object placement, while alignof reports a type's alignment. section 12.7
  • Removing alignas from valid code does not change its semantics, but it can remove an optimization opportunity. section 15.0

How Modern C covers it

How deep it goes
Explains syntax, type-or-expression arguments, examples, performance motivation, and the Effective Type Rule limitation, but defers specialized details.
Examples
Uses complex values, float arrays, unsigned byte storage, alignment measurements, offset traversal, and a bus-error experiment.
What you can do after
Apply it via C11 syntax to request type- or expression-based alignment for objects and members.
How it connects
Connects alignment with alignof, the C memory model, cache boundaries, optimization, and the Effective Type Rule.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.