关于循环缓冲区中简洁索引处理的建议
我已经实现了一个循环缓冲区,并且我想要一种简洁的方法来更新缓冲区指针,同时正确处理环绕。
假设数组大小为 10,我的第一反应类似于:
size_t ptr = 0;
// do some work...
p = ++p % 10;
静态分析以及 gcc -Wall -Wextra 正确地惩罚了我由于序列点违规而导致的未指定行为。明显的修复类似于:
p++;
p %= 10;
但是,我一直在寻找更简洁的东西(即单行代码)来“封装”此操作。建议?除了p++; p%= 10; :-)
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; :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
或者避免取模:
or to avoid the modulo:
与 p++ 不同; p%=10;,我相信使用逗号运算符,如
p++, p%=10;
更符合“单行”的资格。您可以在宏或循环体或不带大括号的 if/else 语句中使用它,并且它的计算结果为p
的结果值。Unlike
p++; p%=10;
, I believe using the comma operator as inp++, 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 ofp
.您是否考虑过
++p %= 10;
Have you considered
++p %= 10;