Search code examples
cc99sequence-points

Suggestions for concise index handling in circular buffer


I've implemented a circular buffer, and I would like a concise means of updating the buffer pointer while properly handling the wrap-around.

Assuming an array of size 10, my first response was something like:

size_t ptr = 0;  
// do some work...
p = ++p % 10;

Static analysis, as well as gcc -Wall -Wextra, rightly slapped my wrist for unspecified behavior due to a sequence point violation. The obvious fix is something like:

p++;
p %= 10;

However, I was looking for something more concise, (i.e., a one-liner) to "encapsulate" this operation. Suggestions? Other than p++; p%= 10; :-)


Solution

  • p = (p + 1) % N;
    

    or to avoid the modulo:

    p = ((N-1) == p) ? 0 : (p+1);