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:
// 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; } |
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:
// 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'; } |
alignment of Geeks : 4 sizeof of Geeks : 12 alignment of int : 4 sizeof of int : 4
Recommended Posts:
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- set operator= in C++ STL
- map::operator[] in C++ STL
- new vs operator new in C++
- map operator= in C++ STL
- dot (.) operator in C/C++
- unordered_set operator!= in C++ STL
- std::basic_string::operator[] in C++
- unordered_set == operator in C++ STL
- multimap::operator= in C++ STL
- array::operator[ ] in C++ STL
- deque::operator= and deque::operator[] in C++ STL
- vector::operator= and vector::operator[ ] in C++ STL
- list::operator= in C++ STL
- unordered_map operator= in C++ STL
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.



