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

后端 未结 12 801
予麋鹿
予麋鹿 2021-02-01 03:29

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 == \         


        
12条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 04:19

    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.

提交回复
热议问题