By dpagan on May 16, 2007
Beginning with the Sun Studio 12 C compiler, the __alignof__ keyword (a gcc extension) will be accepted (see "Inquiring on Alignment of Types or Variables" in the gcc docs)
The syntax for __alignof__ is exactly like "sizeof", but it evaluates to the required, or optimal, alignment for a type or an object. It can be used in a variety of ways. For example, in situations where you want to specify an alignment larger than would normally be chosen, you can use this keyword in combination with __attribute__. Let's say you have an array of char and you want to change the eventual alignment from the default of "1" to that of the natural alignment of "int". Here's how it can be done -
unsigned char foo __attribute__ ((aligned(__alignof__(int))));
Or perhaps there's some code somewhere that relies on data being aligned on a certain boundary. The __alignof__ keyword can be used to easily check the alignment -
if (buffer % __alignof__(<aligned_data>)) ...
Or it can be used to simplify the specification of macros. For example -
\* Largest alignment size needed, minus one.
#define ALBYTES (__alignof__ (long double) - 1)
/\* Align P to ALBYTES \*/
#define AL(p) (((unsigned long int) (p) + ALBYTES) & ~ALBYTES)
- If the operand to __alignof__ is an lvalue rather than a type, the value returned is the alignment of the lvalue;
- No parentheses are required around expressions.