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

后端 未结 12 802
予麋鹿
予麋鹿 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 03:57

    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.

提交回复
热议问题