c - 再执行一次 while 循环的标准用法

标签 c while-loop idioms

C 中是否有一种模式可以再执行一次 while 循环。 目前我正在使用

while(condition) {
    condition = process();
    // process() could be multiple lines instead of a function call
    // so while(process());process(); is not an option
}
process();

如果进程是多行而不是单个函数调用,那就太可怕了。

替代方案是

bool run_once_more = 1;
while(condition || run_once_more) {
    if (!condition) {
        run_once_more = 0;
    }
    condition = process();
    condition = condition && run_once_more;
}

有没有更好的办法?


注意:do while 循环不是解决方案,因为它等同于

process();
while(condition){condition=process();}

我要

while(condition){condition=process();}
process();

根据请求,更具体的代码。 我想从 another_buffer 填充缓冲区并获取 (indexof(next_set_bit) + 1) 进入 MSB,同时保持掩码和指针。

uint16t buffer;
...
while((buffer & (1 << (8*sizeof(buffer) - 1))) == 0) { // get msb as 1
    buffer <<= 1;
    // fill LSB from another buffer
    buffer |= (uint16_t) (other_buffer[i] & other_buffer_mask);
    // maintain other_buffer pointers and masks
    other_buffer_mask >>= 1;
    if(!(other_buffer_mask)) { 
        other_buffer_mask = (1 << 8*sizeof(other_buffer[0]) -1)
        ++i;
    }
}
// Throw away the set MSB
buffer <<= 1;
buffer |= (uint16_t) (other_buffer[i] & other_buffer_mask);
other_buffer_mask >>= 1;
if(!(other_buffer_mask)) { 
    other_buffer_mask = (1 << 8*sizeof(other_buffer[0]) -1)
    ++i;
}
use_this_buffer(buffer);

最佳答案

因为这不是一件很典型的事情,所以不太可能有一个标准的习惯用法来做这件事。但是,我会这样写代码:

for (bool last = 0; condition || last; last = !(condition || last)) {
    condition = process();
}

只要 condition 为真,循环就会执行一次,然后再执行一次,如果 condition 为假,则在循环开始时执行零次。我将您的问题解释为这就是所需的行为。如果不是,并且您总是希望循环至少执行一次,那么 do...while 就是您寻求的成语。

关于c - 再执行一次 while 循环的标准用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29475232/

相关文章:

perl - 是否可以检测当前的 while 循环迭代是否是 perl 中的最后一次?

python - 如果 __name__ == "__main__": do? 会怎样

ruby - 这样做的更 ruby 的方式是什么?

python - Django : Custom save method with queryset

java - while 循环在不同的项目中工作方式不同,但代码结构相同?

python - 利用 python 对可变数据结构(如列表)的传递共享是否符合习惯?

c - 从 OS X 上的 C 中的 dlopen()ed 动态库访问主程序全局变量

检查字符串是否包含字符串

c++ - 我应该停止使用 OpenCV 吗?

c - GCC 4.7.2 优化问题