__alignof__ keyword

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[100] __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.
 \*/
#ifndef ALBYTES
#define ALBYTES (__alignof__ (long double) - 1)
#endif

/\* Align P to ALBYTES  \*/
#ifndef AL
#define AL(p) (((unsigned long int) (p) + ALBYTES) & ~ALBYTES)
#endif

Notes:

  1. If the operand to __alignof__ is an lvalue rather than a type, the value returned is the alignment of the lvalue;
  2. No parentheses are required around expressions.


Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

dpagan

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today