7

I'm using PC Lint for the first time. I was "linting" my code, when PC Lint warns me about my while(TRUE).

This is what it says:

716: while(1) ... -- A construct of the form while(1) ... was found.

Whereas this represents a constant in a context expecting a Boolean, it may reflect a programming policy whereby infinite loops are prefixed with this construct. Hence it is given a separate number and has been placed in the informational category. The more conventional form of infinite loop prefix is for(;;).

I didn't understand this statement. Can anyone help me to understand it?

thetic
  • 174
  • 1
  • 11
Daniel Grillo
  • 2,368
  • 4
  • 37
  • 62
  • 2
    `while(TRUE)` may not be an infinite loop if some one sets `TRUE` to `0` while there is no way for that to happen with `for(;;)`. – Dan D. Sep 23 '11 at 11:31
  • 2
    @Dan D., sure there is - we are talking about the preprocessor after all. How about `#define for(;;) if(0)`? ;-) – Péter Török Sep 23 '11 at 11:34
  • 1
    I know what it's talking about but that's an odd explanation I have to say. – Jeff Mercado Sep 23 '11 at 11:34
  • @PéterTörök: `#define for(;;) if(0)` is illegal because for(;;) is not an identifier and neither can it be parsed as a macro declaration – Armen Tsirunyan Sep 23 '11 at 12:05
  • 1
    @Armen, fair enough, my C skills are rusty. I believe though there may easily be some twisted way to actually do it. And if someone is evil enough to redefine `TRUE`, he can just as well redefine `for` :-( – Péter Török Sep 23 '11 at 12:10
  • Nah, the common convention is while(42), ensures exit after 8 million years. The arbitrarity of the value is enough reason to not use one, for(;;) is a great speed bump to a reader. – Hans Passant Sep 23 '11 at 12:46

2 Answers2

6

The text says that although while(TRUE) (which gets preprocessed into while(1)) is a perfectly valid infinite loop, the more conventional form of writing an infinite loop is

for(;;)
{
   ...
} 

because it doesn't use any values at all and therefore is less error-prone.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
4

It says that the more conventional infinite loop is for(;;), which I'd say is an arguable assertion, and that it's categorized this construct as an "informational category" finding - I suspect that if you used the for(;;) instead it would go away. I've always written these as while(1) and never for(;;) myself. If it does what you expect, I'd ignore the findings of PC LINT on this one or switch it if you're worried about someone redefining TRUE because if someone redefined TRUE your loop wouldn't run at all.

itsmatt
  • 31,265
  • 10
  • 100
  • 164
  • 8
    And anyway, if someone redefined `TRUE`, it would be the least of your woes that a practicular loop doesn't run infinitely :-) – Péter Török Sep 23 '11 at 11:44