Suggestions for concise processing of indexes in a circular buffer

I have implemented a circular buffer, and I would like to get a short way to update the buffer pointer with proper wrapper handling.

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

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

Static analysis, as well as gcc -Wall -Wextra , correctly hit the wrist for unspecified behavior due to a violation of the sequence point. The obvious fix is โ€‹โ€‹something like:

 p++; p %= 10; 

However, I was looking for something more concise (i.e., single-line) to "encapsulate" this operation. Suggestions? Except p ++; p% = 10; :-)

+2
c sequence-points c99
source share
3 answers
 p = (p + 1) % N; 

or to avoid modulo:

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

Unlike p++; p%=10; p++; p%=10; , I believe that using the comma operator, as in p++, p%=10; is better qualified as "single line". You can use it in a macro or in the body of a loop or if / else without bindings, and it evaluates the resulting value of p .

0
source share

Have you considered ++p %= 10;

-2
source share

All Articles