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

跟風遠走 提交于 2019-12-18 12:12:27

问题


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


回答1:


while (condition);

is the same as

while (condition) 
{
}

It can be used for waiting loops, e.g.:

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



回答2:


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;



回答3:


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



回答4:


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



回答5:


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

Programmers often add a space before the semicolon, i.e.

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 (i.e. do the next few lines look like the body of a loop or not?).




回答6:


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

while ( condition() );



回答7:


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.




回答8:


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!




回答9:


It means that keep checking condition until it evaluate to false




回答10:


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.




回答11:


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 e.g. 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 i.e. 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 (i.e. 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 (i.e. condition may need to be more than a simple variable).

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




回答12:


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




回答13:


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




回答14:


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




回答15:


Its just a while loop with no execution body

while(condition);

is same as

while(condition)
{
    }



回答16:


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.



来源:https://stackoverflow.com/questions/4125124/is-the-code-whilecondition-valid-and-what-does-it-mean

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!