Suggestions for concise index handling in circular buffer

余生颓废 提交于 2019-12-11 03:18:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!