【发布时间】:2015-06-11 02:01:31
【问题描述】:
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);
【问题讨论】:
-
process is of multiple lines and not a single function call然后进行(可能是内联的)函数调用。 -
do ... while (condition);在某些情况下还可以提供额外的迭代。 -
@chux 如果在最后一次调用中也修改了条件就可以了。尽管如此,do while 循环会NOT 进行额外的迭代 条件为假。看我的笔记。
-
你能告诉用户更多关于
condition的信息吗?是数字还是什么? -
@black 添加了更多信息。
标签: c while-loop idioms