use*_*551 6 c idioms while-loop
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();
Run Code Online (Sandbox Code Playgroud)
如果进程是多行而不是单个函数调用,那就太可怕了。
替代方案是
bool run_once_more = 1;
while(condition || run_once_more) {
if (!condition) {
run_once_more = 0;
}
condition = process();
condition = condition && run_once_more;
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
注意: do while 循环不是解决方案,因为它等效于
process();
while(condition){condition=process();}
Run Code Online (Sandbox Code Playgroud)
我想要
while(condition){condition=process();}
process();
Run Code Online (Sandbox Code Playgroud)
每个请求,更具体的代码。我想从 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);
Run Code Online (Sandbox Code Playgroud)
那这个呢:
int done, condition = 1;
for (;;) {
...
done = !condition;
condition = process();
if (done) break;
...
}
Run Code Online (Sandbox Code Playgroud)
我并不是说这是一个标准的习惯用法,只是一个临时的黑客。