Namespaces
Variants
Views
Actions

alignof operator (since C++11)

From cppreference.com
< cpp‎ | language
Revision as of 22:53, 2 November 2012 by P12bot (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Initialization
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

Queries alignment requirements of a type

Contents

Syntax

alignof( Template:sparam )

Returns an object of type std::size_t.

Explanation

Returns alignment in bytes (an integer power of two) required for any instance of the given type, which is either complete type, an array type, or a reference type.

If the type is reference type, the operator returns the alignment of referenced type; if the type is array type, alignment requirement of the element type is returned.

The types char, signed char, and unsigned char have the weakest (smallest) alignment supported by the implementation.

Keywords

alignof

Example

#include <iostream>
 
struct Empty {};
 
struct Foo {
     int f2;
     float f1;
     char c;
};
 
int main()
{
    std::cout << "alignment of empty class: " << alignof(Empty) << '\n'
              << "alignment of pointer : "    << alignof(int*)  << '\n'
              << "alignment of char : "       << alignof(char)  << '\n'
              << "alignment of Foo : "        << alignof(Foo)   << '\n' ;
}

Output:

alignment of empty class: 1
alignment of pointer : 8
alignment of char : 1
alignment of Foo : 4

See also

Template:cpp/language/dcl list alignas
obtains the type's alignment requirements
(class template) [edit]