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: alignment requirement of the element type is returned.
  • reference type: the operator returns the alignment of referenced type.

Return Value: The alignof operator typically used to returns a value of type std::size_t.

Program:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demonstrate alignof operator
#include <iostream>
using namespace std;
  
struct Geeks {
    int i;
    float f;
    char s;
};
  
struct Empty {
};
  
// driver code
int main()
{
    cout << "Alignment of char: " << alignof(char) << endl;
    cout << "Alignment of pointer: " << alignof(int*) << endl;
    cout << "Alignment of float: " << alignof(float) << endl;
    cout << "Alignment of class Geeks: " << alignof(Geeks) << endl;
    cout << "Alignment of Empty class: " << alignof(Empty) << endl;
  
    return 0;
}

chevron_right


Output:

Alignment of char: 1
Alignment of pointer: 8
Alignment of float: 4
Alignment of class Geeks: 4
Alignment of Empty class: 1

alignof vs sizeof:
The alignof value is the same as the value for sizeof for basic types. Consider, this example:

typedef struct { int a; double b; } S;  
// alignof(S) == 8  

Above case, the alignof value is the alignment requirement of the largest element in the structure.
Example program to demonstrate the difference between alignof and sizeof:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demonstrate
// alignof vs sizeof operator
#include <iostream>
using namespace std;
  
struct Geeks {
    int i;
    float f;
    char s;
};
  
int main()
{
  
    cout << "alignment of Geeks : " << alignof(Geeks) << '\n';
    cout << "sizeof of Geeks : " << sizeof(Geeks) << '\n';
    cout << "alignment of int : " << alignof(int) << '\n';
    cout << "sizeof of int     : " << sizeof(int) << '\n';
}

chevron_right


Output:

alignment of Geeks : 4
sizeof of Geeks : 12
alignment of int : 4
sizeof of int     : 4


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.