Is using a while block to do nothing a bad thing?

Well if you really don't like the empty braces, you could refactor that inner loop into

while (c == ' ') {c = getchar();}

This costs one extra comparison though, so a do while loop would be better.


I think it is perfectly acceptable.

I would either write it:

//skip all spaces
while ((c = getchar()) == ' ') {} 

to make it obvious that this one line of code does one thing.

Or I would write it like this:

while ((c = getchar()) == ' ') {
    //no processing required for spaces
}

so that it matches the rest of your code's format.

Personally, I am not a fan of the

while ((c = getchar()) == ' ');

format. I think it is to easy to overlook the semi-colon.


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.


Your question "Is using a while block to do nothing a bad thing?" may also be answered in terms of wasting CPU cycles. In this case the answer is "No", since, the process will sleep while it waits for the user to input a character.

The process will wake only after a character is input. Then the test will occur and if the test passes, i.e. c == ' ', the process will go to sleep again until a the next character is entered. This repeats until a non-space character is entered.

Tags:

C

While Loop