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

后端 未结 12 796
予麋鹿
予麋鹿 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:56

    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.

    0 讨论(0)
  • 2021-02-01 03:56

    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)

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-01 03:59

    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.

    0 讨论(0)
  • 2021-02-01 04:02

    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.

    0 讨论(0)
  • 2021-02-01 04:02

    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.

    0 讨论(0)
提交回复
热议问题