Tuesday 8 July 2008

What's wrong with this line?

A colleague recently hit this problem when writing some anti-aliasing code.

Imagine you have a block of data in memory, and want to sum blocks of 4 contiguous values. If ptr points to the block of memory do you know what's wrong with this line?
result = *ptr++ + *ptr++ + *ptr++ +*ptr++;

The post-increment operator isn't evaluated until the ; so in effect this code could be doing:
result = *ptr + *ptr + *ptr + *ptr;
ptr += 4;

However it's not even that straightforward. The C++ standard says that variables can only be modified once between sequence points so the result of the first line is undefined.

Writing the code as:
result = *ptr + *(ptr+1) + *(ptr+2) + *(ptr+3);
result += 4;
is much clearer and avoids any unexpected side effects, even though it is a little less efficient.  After all you know what they say about premature optimisation, don't you.

It's really best not to try and be too clever with C/C++ unless it's absolutely necessary and you really know what you're doing.

No comments: