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;
} |
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:
// 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' ;
} |
Output:
alignment of Geeks : 4 sizeof of Geeks : 12 alignment of int : 4 sizeof of int : 4
Article Tags :