Monday, November 10, 2008

Useful C macro's

Some useful macro's and functions I will go over are align macros.

#define ALIGN(x, a) __ALIGN((x), (a) - 1)
#define __ALIGN(x, a) (((x) + (a)) & ~(a))
#define IS_ALIGNED(x, a) ( ((x) & ((a) - 1)) == 0 )

These macro's are used to identify the proper alignment. They use the bitwise operations extensively. Also, another set of macro's that are useful to know are rounding macros.

#define ROUND_UP(x, y) ( (((x) + (y) - 1) / (y)) * (y) )

Another macro that is seen throughout the internet is the sizeof operator. Although, it is not officially a macro, it is a compiler-specific operator. However, it should be equivalent to the following macro's:

#define sizeof_value(val) ( (size_t)((&val + 1) - &val) )
#define sizeof_type(type) ( (size_t)((type *)0 + 1) )

These are small tricks that can retrieve the types by casting to pointers and checking the pointer arithmetic.

No comments: