用于再次执行while循环的标准习惯用法

时间:2015-04-06 16:25:23

标签: c while-loop idiomatic

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);

4 个答案:

答案 0 :(得分:1)

这个怎么样:

int done, condition = 1;
for (;;) {
    ...
    done = !condition;
    condition = process();
    if (done) break;
    ...
}

我并不是说这是一个标准的习惯用语,只是一个特别的黑客。

答案 1 :(得分:1)

因为这不是一个非常典型的事情,所以不太可能有这样做的标准习语。但是,我会写这样的代码:

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

只要condition为真,循环就会执行,然后再循环一次,如果循环开始时condition为假,则循环为零。我将您的问题解释为意味着这是期望的行为。如果没有,并且你总是希望循环至少执行一次,那么do...while就是你寻求的习语。

答案 2 :(得分:0)

我用这个:

bool done = false;
do {
  if (!condition) done = true;
  condition = process();
} while (!done);

一个不太可读的黑客,假设condition未预定义:

for (bool condition=true, done=false;
     !done && (condition || done = true);
    ) {
  condition = process();
}

答案 3 :(得分:0)

我遇到了同样的问题,我的解决方法是:

仅当您确定要至少运行一次process()时:

for property in editableProperties:
    # Lets suppose this parses values from a form in a request to the needed type
    new_value = deserialize(property._kind, self.request.get(property._name))
    setattr(item, property._name, new_value)

如果不确定:

None

例如:

while(1){
    process();
    if(!condition()) break;
    /*The loop breaks before bad things happen*/
    things_you_want_to_happen_only_while_condition_is_true();
}