Padding and Alignment

Understanding Natural Alignment

How do I know what the natural alignment of a type should be?

Abstract art representing computer programming

Natural alignment is typically based on the size of the data type. Here's a practical guide to common alignment requirements:

#include <iostream>

int main() {
  std::cout << "Alignment requirements:\n"
    << "char: " << alignof(char) << " bytes\n"
    << "short: " << alignof(short) << " bytes\n"
    << "int: " << alignof(int) << " bytes\n"
    << "long: " << alignof(long) << " bytes\n"
    << "float: " << alignof(float) << " bytes\n"
    << "double: " << alignof(double) << " bytes\n"
    << "pointer: " << alignof(int*) << " bytes\n";
}
Alignment requirements:
char: 1 bytes
short: 2 bytes
int: 4 bytes
long: 8 bytes
float: 4 bytes
double: 8 bytes
pointer: 8 bytes

For compound types like structs and classes, the alignment is typically determined by the largest alignment requirement of any member:

#include <iostream>

struct Example {
  char A;// 1 byte alignment
  double B;// 8 byte alignment
  int C;// 4 byte alignment
};

int main() {
  std::cout << "Struct alignment: "
    << alignof(Example) << " bytes\n";
}
Struct alignment: 8 bytes

You can use the alignas specifier to request specific alignment:

#include <iostream>

struct alignas(16) Custom {
  int Value;
};

int main() {
  std::cout << "Custom alignment: "
    << alignof(Custom) << " bytes\n";

  // This will always start at a 16-byte boundary
  Custom Instance;
}

Remember:

  • Basic types are usually aligned to their size
  • Compound types align to their largest member
  • The alignof() operator tells you alignment requirements
  • Arrays align to their element type's requirements
  • Alignment is always a power of 2
This Question is from the Lesson:

Padding and Alignment

Learn how memory alignment affects data serialization and how to handle it safely

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Padding and Alignment

Learn how memory alignment affects data serialization and how to handle it safely

sdl2-promo.jpg
Part of the course:

Game Dev with SDL2

Learn C++ and SDL development by creating hands on, practical projects inspired by classic retro games

Free, unlimited access

This course includes:

  • 75 Lessons
  • 100+ Code Samples
  • 91% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2025 - All Rights Reserved