Can we put semicolon like while(condition);
in a C Programming?
If while(condition);
is valid, what does it mean?
-
5Yes, unfortunately, as I found out after a few wasted hours in my first programming class.– ChanceCommented Nov 8, 2010 at 22:24
-
Condition is irrelevant, all of them evaluate to either true or false. Granted, things can be done inside the condition as discussed below, but this question appears to be mostly about syntax and/or behavior as related to the loop.– ChanceCommented Nov 8, 2010 at 22:30
-
Yes, it's valid. How else would you write a do-while loop?– endolithCommented Feb 8, 2012 at 15:22
16 Answers
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();
-
46It should be noted that this will result in execution continually looping and checking the condition, so the process/thread does not actually wait but use CPU time all the time. Commented Nov 8, 2010 at 15:27
-
5@GCATNM: right, but sometimes (e.g. controller applications waiting for a signal) there is really nothing else to do than just wait. If this is not the desired behavior the loop body should allow thread/task switching (e.g. using sleep) or use another mechanism for waiting (e.g. call-back-functions, interrupts); but this was not the question...– CurdCommented Nov 8, 2010 at 15:37
-
12@Brian and also busy-wait :)– user124493Commented Nov 8, 2010 at 15:42
-
3Condition may also include action as well, it's an arbitrary expression evaluation after all. So that this whole discussion is ridiculous IMHO. All the bla-bla bout processor loads, spin-locking, blocking, shmocking, etc.– valdoCommented Nov 8, 2010 at 17:21
-
3The comment is true whether the condition blocks or not. If it blocks, the name is poorly chosen, and the loop is unnecessary. If it does not block, the example is poorly chosen -- its most frequent usage by beginners is as an anti-pattern. Commented Nov 8, 2010 at 18:40
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;
-
8+1 for the explanation that it's useful when the loop condition has a side effect. -100000 for putting the semicolon on a separate line! Horrible! FWIW, there is a good crossposted flamewar going on on comp.lang.java.programmer/comp.lang.c about how to style this construct which may be of interest. Commented Nov 8, 2010 at 15:36
-
8
while (condition) continue;
(with a line break before the continue and/or braces, as you prefer) has been suggested as a readable and reasonably uncontrived form. Commented Nov 8, 2010 at 15:43 -
2As I mentioned, I use braces rather than a semicolon. K&R did use the semicolon, on a separate line. The "continue" pattern seems an improvement. I don't consider flamewars on the small stuff to be valuable. Commented Nov 8, 2010 at 16:09
-
5Can we have another flame war over the reversed condition? I strongly prefer '
while ((*pt++ = *ps++) != '\0')
, but that's the beauty of flame wars. (FWIW: I prefer the semi-colon on its own on the next line.) Commented Nov 8, 2010 at 17:53 -
I was thinking of adding a similar example, but perhaps with different style. Style aside, this is a good example of a common use of an empty "while" body.– Lee-ManCommented Nov 8, 2010 at 18:03
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++));
-
1While this may be an example of an empty body loop it is also an example of poorly designed code (hence a little less useful IMHO).– Lee-ManCommented Nov 8, 2010 at 18:04
-
@Lee-Man - exactly, I even point out that it's not a good idea, the logic belongs in the body of the loop. My second example is a little better, if only because it's a somewhat common pattern and most C programmers would recognize it instantly. Commented Nov 8, 2010 at 18:07
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);
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?).
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.
-
condition without side-effects also makes sense if it checks volatile variable, when it just waits for asynchronous event.– VovaniumCommented Nov 8, 2010 at 23:09
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!
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 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!
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).
-
4Unless you're waiting on something from another thread or a register to change (or something similar). i think you've over-generalized it.– user124493Commented Nov 8, 2010 at 15:45
-
2This is true in a single threaded program, but the value of condition could be changed by other threads. Commented Nov 8, 2010 at 15:45
-
2
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)
{
}
-
We have a coding standard at work that always requires us to use braces even for simple if/while/for statements. This may be a good reason why; the second statement is so much clearer.– ChanceCommented Nov 8, 2010 at 22:27
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.
-
1I consider this an anti-pattern. For heavens sake, just use return, or even goto where it's the better construct. Don't write code with goto's masquerading as structured. Commented Nov 8, 2010 at 20:51