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 == \
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.
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 thinks no problem in it. You can use it, In many situations i prefer it.
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.
The canonical way — used since time immemorial, have a look, eg, at the Lyons book — is
while(condition) // Here's the whole thing
; // empty body.
In fact, in general the 'semicolor on a separate line' convention is used for a null statement. You will, for example, occassionally see
if( condition-1)
;
else if (condition-2)
stmt;
else {
// do stuff here
}
It's a lot more uncommon, but shows up either where condition-1 is very complicated, so you don't want to negate it and chance confusion, or where the code has been hand-optimized within an inch of its life, so that you want the most common case first.
The
while(condition) ;
form is to be slavishly avoided, because that's a common and annoying typo: you should make it clear that you did it on purpose. Empty braces
while(condition){
}
or its variants, are also trouble because they either don't stand out enough, or worse lead to other typos.
I've used code like this. I don't think there's really any reason not to use it if the situation warrants it.