What is the proper equivalent of "while (true)" in plain C?

Since C does not have bools, which eigen variable is placed instead truein the algorithm that uses

do
{
   // ... 
} while(true);

???

If the correct C programmer is executing

do
{
   // ... 
} while(1);

or is there a specific variable reserved to mean "something that is not null / null"?

+4
source share
4 answers

I usually see now

while(1) {
    ...
}

Used to be met

for(;;) {
    ...
}

All this makes sense.

+10
source

Your question is not really about bool(which modern C has, if you have #include <stdbool.h>), is the best way to write an infinite loop.

Common idioms:

while (1) {
    /* ... */
}

and

for (;;) {
    /* ... */
}

, . for ; , , , , true.

while (1), , , . for (;;), , , () .

(while (1 + 1 == 2) et al., .

+10

c89:

:

typedef int bool;
#define true 1
#define false 0

:

/* Boolean constants. */
#define TRUE 1
#define FALSE 0

int .

( ) c99:

#include <stdbool.h>

, , c89.

http://en.wikipedia.org/wiki/C_data_types#stdbool.h

+5

C has a header file stbool.hfor using variables bool.

So it works

#include <stdio.h>
#include<stdbool.h>
int main(void) {
    int i=1;
    while(true)
    {
        if(i==3){       
        break;
        }
        printf("%d\n",i);
        i++;
    }
return 0;
}

Output

1  
2

note: Modern C99 supports variables bool, but C89 / 90 does not.

If you use C89 / 90, you can use typedefeither constants, as indicated in one of the answers here, or you can use the enumssame as this

   typedef enum {false, true } bool;    
   bool b=true;
   int i=1;
   while(b)
   {
        if(i==3){       
        break;
        }
        printf("%d\n",i);
        i++;
    }

Output

1  
2

You can check this bool in C

Hope this helps you.

+3
source

All Articles