I\'m currently working through the excercises in \'The C Programming Language\'. Here\'s one of my solutions:
int c;
while ((c=getchar()) != EOF) {
if (c == \
Not at all - I believe you'll find do-nothing loops like these in K&R, so that's about as official as it gets.
It's a matter of personal preference, but I prefer my do-nothing loops like this:
while(something());
Others prefer the semicolon to go on a separate line, to reinforce the fact that it's a loop:
while(something())
;
Still others prefer to use the brackets with nothing inside, as you have done:
while(something())
{
}
It's all valid - you'll just have to pick the style you like and stick with it.
I don't think the procedure is, but your formatting is pretty weird. There's nothing wrong with:
/* Eat spaces */
while ((c = getchar()) == ' ');
(that is, indicate there's intentionally not a body)
A while
that does nothing probably is a bad thing:
while(!ready) {
/* Wait for some other thread to set ready */
}
... is a really, really, expensive way to wait -- it'll use as much CPU as the OS will give it, for as long as ready
is false, stealing CPU time with which the other thread could be doing useful work.
However your loop is not doing nothing:
while ((c = getchar()) == ' ')
{}; // skip
... because it is calling getchar()
on every iteration. Hence, as everyone else has agreed, what you've done is fine.
Well, not really but it depends on your architecture.
if (dosomething()) { ; }
The above is going to constantly be pushing and popping from your local stack, which has a memory overhead. Also, you will also be flushing your processors' pipelines with noop operations.
I would favor:
while ((c = getchar()) == ' ') /* Eat spaces */;
I've also been known to have a procedure named DoNothing specifically for calling in cases like this. It makes it very clear that you really mean to do nothing.
While non-existent loop bodies are perfectly acceptable it should be VERY clear that it's intentional.
An alternative option which hasn't been mentioned yet:
while(condition)
(void)0;
I really do not prefer to write my loops this way, but I had a TA last semester who did.