Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Alignas in C++ 11
Next article icon

Alignas in C++ 11

Last Updated : 06 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The alignas is a type specifier which was introduced in C++11. It provides custom alignment to variables and user-defined datatypes like class and struct. Alignment refers to the memory address at which an object's data should begin. alignas allows the programmer to control how the compiler aligns data in memory. It may allocate memory address in modulo power of 2 to improve performance, especially on architectures that require data to be aligned.

Syntax

alignas( Integral_constant_expression )

The alignas Specifier applies for:

  • Declaration or definition of a struct, class, union, enum.
  • Declaration of a non-bitfield class data member.
  • Declaration of a variable, except
    • a function parameter.
    • the exception parameter of a catch clause.

Note: We would require the knowledge of alignof specifier to work with our example.

Example of alignas Specifier

C++
// C++ program to illustrate the use of alignas specifier #include <iostream> using namespace std;  // struct is aligned to 16 bytes in memory. struct alignas(16) Demo {      int var1l; // 4 bytes     int var2; // 4 bytes     short s; // 2 bytes     // char aligned to 4 bytes in memory.     alignas(4) char arr[5]; };  // driver code int main() {     cout << alignof(Demo) << endl; // output: 16     return 0; } 

Output
16  

Explanation

Here, the output is 16, solely because we have used alignas(16) for the struct Demo. But what about the various member inside the struct? For example, int var1 and int var2 are int types and it is aligned to 4 bytes. Also, alignas(4) char arr[5] specifies that the 'char' array needs to be aligned to 4 bytes (instead of 1 byte).
So the compiler decides to choose the largest (in other words, strictest) alignment requirement among the members and the struct itself. Hence, 16 which is the largest alignment, is chosen as output when alignof operator is called on struct Demo. Finally, we get to know that all objects of the Demo struct will be aligned to 16 byte boundaries in memory.

Practice: Try to use sizeof(Demo) and compare it with alignof(Demo) and check the difference if any.

Real Time Use Cases of alignas

The alignas specifier is generally used to the following cases:

  • To avoid unnecessary invalidation of your data from cache lines in multi-threaded application.
  • To optimize the CPU reads such that wastage of CPU cycles can be saved.
  • To implement custom memory layout.

Next Article
Alignas in C++ 11

V

viveksinghvds
Improve
Article Tags :
  • C++
  • C++ 11
Practice Tags :
  • CPP

Similar Reads

    alignof operator in C++
    In C++11 the alignof operator used to returns the alignment, in bytes of the specified type. Syntax: alignof(type) Syntax Explanation: alignof: operator returns the alignment in byte, required for instances of type, which type is either complete type, array type or a reference type. array type: alig
    2 min read
    std::string::assign() in C++
    The member function assign() is used for the assignments, it assigns a new value to the string, replacing its current contents. Syntax 1: Assign the value of string str. string& string::assign (const string& str) str : is the string to be assigned. Returns : *this CPP // CPP code for assign
    5 min read
    STD::array in C++
    The array is a collection of homogeneous objects and this array container is defined for constant size arrays or (static size). This container wraps around fixed-size arrays and the information of its size are not lost when declared to a pointer. In order to utilize arrays, we need to include the ar
    5 min read
    Assignment Operators in C++
    In C++, the assignment operator forms the backbone of computational processes by performing a simple operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in any programming language i.e. assign some value to the variables in
    6 min read
    std::distance in C++
    The std::distance() in C++ STL is a built-in function used to calculate the number of elements between two iterators. It is defined inside <iterator> header file. In this article, we will learn about the std::distance function in C++ with examples.Example:C++// C++ Program to illustrate the us
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences