miércoles, 11 de enero de 2012

C++ MACRO Nightmare

This afternoon I was implementing a typical circular buffer including some lines like this to make the pointers go from the end of the buffer to the beginning again when needed.
_bufferReadPos = (_bufferReadPos + len) % BUFFER_SIZE;

When testing the code I started to see very weird values of the read and write pointers, in fact much bigger than expected.

After at least 10 minutes trying to debug the problem I realized that it was because of the expansion of the BUFFER_SIZE macro that was:
#define BUFFER_SIZE 32*1024

% Has precedence over * and my code was been interpreted as:
_bufferReadPos = ((_bufferReadPos + len) % 32) * 1024;
Very sad and not easy to catch.  My solution has been using parenthesis in the BUFFER_SIZE definition to avoid it being split again when being part of the previous line:
#define BUFFER_SIZE (32*1024)

Do you have similar nightmare stories with macros?!

No hay comentarios:

Publicar un comentario