views:

66

answers:

3

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; :-)

+7  A: 
p = (p + 1) % N;

or to avoid the modulo:

p = ((N-1) == p) ? 0 : (p+1);
Oli Charlesworth
+1 almost ... if it weren't for the ugly `(9 == p)` LOL
pmg
Heh, "p = (p + 1) % N" it is.
Throwback1986
A: 

Have you considered ++p %= 10;

swestrup
++p is not modifiable in `C`. Don't know about `C++` or `Java` (question is not tagged with these languages)
pmg
Ah right. I just checked and it isn't modifiable in C. Another place where I've gotten tripped up in the differences between the languages.
swestrup
A: 

Unlike p++; p%=10;, I believe using the comma operator as in p++, p%=10; better qualifies as a "one-liner". You can use it in a macro or in the body of a loop or if/else statement without braces, and it evaluates to the resulting value of p.

R..