问题
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; :-)
回答1:
p = (p + 1) % N;
or to avoid the modulo:
p = ((N-1) == p) ? 0 : (p+1);
回答2:
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
.
回答3:
Have you considered ++p %= 10;
来源:https://stackoverflow.com/questions/3882343/suggestions-for-concise-index-handling-in-circular-buffer