Useful idioms for C/C++ programming

To double integer n:

n << 1

To divide by 2 as integer:

n >> 1

To check if n is even integer:

if(n&1)

Idioms below are due to Adam Peterson.
Instead of

HelloTelegram* telegram = malloc(sizeof HelloTelegram)
// if we need to change type, we will need to change in 2 places

better:

HelloTelegram* telegram = malloc(sizeof *telegram)
// if we need to change type, we will need to change in 1 place only!

sizeof *telegram is computed at compile time!
Size of array by division:

struct pollfd handles[NO_OF_HANDLES] = {0};
const size_t NUM_OF_HANDLES = sizeof handles / sizeof handles[0];

NUM_OF_HANDLES is computed at compile time and is tied to the constant NO_OF_HANDLES!
Combine assert statement and comment about its context into one line:

void some_function(SomeType *some_ptr){
    assert(some_ptr && "is validated by caller");
    //... do something
}

If assertion fails, the string will be outputted to standard-error stream making it easier to debug!

Advertisements
This entry was posted in C++, Productivity, Programming and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s