简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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