简体   繁体   English

在c中执行while循环条件

[英]do while loop condition in c

Does the two code snipets below do exactly the same thing? 下面的两个代码片段是否做完全相同的事情?

do
{
    Delay_us(1);
    status = fetchStatus();
}while(!status);

Second snipet -> 第二个片段->

do
{
    Delay_us(1);
}while(status = fetchStatus(), !status);

which is preferable? 哪个更好?

You can do: 你可以做:

do
{
    Delay_us(1);
} while( !fetchStatus() );

That way you do not need to create a local variable if you do not use it. 这样,如果使用局部变量,则无需创建局部变量。

Yes, they do the same, but I would prefer the following: 是的,他们也这样做,但我希望以下几点:

do {
    Delay_us(1);
} while (!(status = fetchStatus()));

As it streamlines it all together into one statement, not two. 由于它将所有内容简化为一个语句,而不是两个。

They have the same logical output. 它们具有相同的逻辑输出。 In each case status is assigned and then evaluated, but the first is much more readable. 在每种情况下,都将分配状态,然后进行评估,但第一种方法更具可读性。 In general dont use the comma operator. 通常不要使用逗号运算符。

They are equivalent. 它们是等效的。 Since they're equivalent, neither is preferred. 由于它们是等效的,因此都不是首选。 Some people may like the first more aesthetically because it's more familiar, however. 但是,有些人可能更喜欢美学,因为它更加熟悉。

Do you really intend to delay before the first check of status? 您是否真的打算推迟首次检查状态?

I'm by no means an expert, but I believe we're getting into the realm of compiler optimization. 我绝不是专家,但我相信我们正在进入编译器优化领域。 It really depend on which compiler you use to generate the binary from that code. 这实际上取决于您使用哪个编译器从该代码生成二进制文件。 One compiler may take code like your first snippet and optimize it into binary code that effectively does what your second snippet does. 一个编译器可能会像您的第一个代码片段那样使用代码,并将其优化为二进制代码,从而可以有效地执行您的第二个代码片段。

怎么样:

for(; !fetchStatus(); Delay_us(1));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM