关于在循环缓冲区中进行简洁索引处理的建议 [英] 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.
假设数组的大小为10,我的第一个响应是这样的:
Assuming an array of size 10, my first response was something like:
size_t ptr = 0;
// do some work...
p = ++p % 10;
静态分析以及 gcc -Wall -Wextra 正确地拍了拍我的手腕,以防由于序列点冲突而导致未指定的行为.显而易见的解决方法是:
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;
但是,我正在寻找更简洁的东西(即单线)来封装"此操作.有什么建议吗?除 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; :-)
推荐答案
p = (p + 1) % N;
或避免取模:
p = ((N-1) == p) ? 0 : (p+1);
这篇关于关于在循环缓冲区中进行简洁索引处理的建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!