简体   繁体   中英

Is the code “while(condition);” valid and what does it mean?

Can we put semicolon like while(condition); in a C Programming? If while(condition); is valid, what does it mean?

while (condition);

is the same as

while (condition) 
{
}

It can be used for waiting loops, eg:

while (!isLightGreen()); // waits until isLightGreen() returns true
go();

It means the body of the loop is empty. Typically this pattern is used when the condition itself does some work.

For example, this loop can copy bytes within the condition:

while ( '\0' != (*pt++ = *ps++))
            ;

If you're using a semicolon, it's a good idea to put it on a separate line so that it looks less like a mistake. I personally tend to use empty braces -- {}, and sometimes a comment that the empty block is intentional.

Edit:

In the second comment, Tom Anderson notes an improvement over a lone semicolon. Google's C++ style guide recommends either this or {}.

while ( '\0' != (*pt++ = *ps++))
            continue;

Because the condition may actually have side effects, such a construct is allowed. Consider the following:

while (*p && *p++ != ' ');

This would advance the p pointer to the first character that is a space.

You may even use the comma operator to have ordinary statements inside the condition:

while (do_something(), do_something_else(), i < n);

Because statements connected with the comma operator evaluate to the rightmost statement, in that case i < n , the above is identical to:

do {
  do_something();
  do_something_else();
} while (i < n);

Yes, you can. It just means that the while loop will keep looping until condition is false. For example:

#include<stdio.h>

int x = 10;
int func()
{
  printf("%d\n", x);
  return --x;
}

int main()
{
  while(func());
  return 0;
}

But generally people don't do this, as it would make more sense to put the logic in the body of the loop.

Edit:

There are some examples of this in use, for example, copying a null-terminated string:

char dest[256];
char *src = "abcdefghijklmnopqrstuvwxyz";
while(*(dest++) = *(src++));

It will keep evaluating condition until it's false. It is a loop without a body.

Programmers often add a space before the semicolon, ie

while(condition) ;

or empty braces:

while(condition) {}

to show the empty body is intentional and not just a typo. If you are reading some existing source code and wondering why there is an empty loop there you should read the next few lines as well to see if the semicolon should really be there or not (ie do the next few lines look like the body of a loop or not?).

Yes, it's correct. It will loop the condition until it's false.

while ( condition() );

I always write this as:

while (condition())
    continue;

So that it's obvious that it wasn't a mistake. As others have said, it only makes sense when condition() has side effects.

while() is a loop. You're probably looking to do a "do-while" loop. Do-while loops run in this format:

do
{
    // Your process
    // When something goes wrong or you wish to terminate the loop, set condition to 0 or false
} while(condition);

The one you have listed above, however, is an empty loop.

while() loops work nearly the same; there is simply no "do" portion.

Good luck!

这意味着继续检查条件,直到它评估为false

The key to understanding this is that the syntax of the while loop in "C" is as follows:

while (condition) statement

Where statement can be any valid "C" statement. Following are all valid "C" statements :

{ statements } // a block statement that can group other statements

statement; // a single statement terminated by a ;

; // a null statement terminated by a ;

So, by the rules of the while loop , the statement part (null statement in your example) will execute (do nothing) as long as condition is true . This is useful because it amounts to a busy wait till the condition turns false . Not a good way to wait, but useful nevertheless. You could use this construct, for example, if you want to wait for another thread (or a signal handler) to set a variable to some value before proceeding forward.

The code while(condition); is perfectly valid code, though its uses are few. I presume condition is a variable, not a function — others here discuss functional condition .

One use of while(condition); may be to block while waiting for a signal eg SIGHUP , where the signal handler changes the variable condition . However, this is usually not the best way to wait for a signal. One would typically use a sleep in the loop ie while(condition) { sleep(1); } while(condition) { sleep(1); } .

The absence of any sleep means that the loop will be continually processing in the interim, and likely wasting processing cycles. Unless the process has its resources managed (and even there...), I think this is only suitable where the loop needs to be broken in an interval less than the granularity of the available sleep command (ie sleep is granulated by the second, but you need the code after the look executed with sub-second response time). That being said, a blocking pipe or socket may be preferable to signals, performance wise – though I don't have any emperical data to back that up offhand, and I suspect performance may vary significantly depending on the platform.

One could have condition modified by a parallel thread of the same process, but I'd think one should prefer to do that by way of a mutex or semaphore (ie condition may need to be more than a simple variable).

I hope that's helpful, or at least food for thought!

It is just an empty loop. It would help if you explained what the condition is.

If the evaluation of the condition does not modify a value that influences the condition itself, while(condition); is an empty infinite loop, meaning it will never terminate (and never do anything except consuming CPU time).

it is absolutely correct. it means doing nothing in the loop,just polling the condition.And it is common in embedded system`s codes.

Its just a while loop with no execution body

while(condition);

is same as

while(condition)
{
    }

Just another usage not described here:

do
{
   if(out_of_memory)
     break;

   if(file_does_not_exist)
     break;

   return ok;

} while(0);

return error;

This allows you to avoid several return calls or goto statements.

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