简体   繁体   中英

While-loop in c

what is different between while(0) and while (1 or another number ) ??

int main() {
   do {
      printf("Math ");
   } while (0);

   printf("Computer");
}

while (cond) { ... } and do { ... } while (cond); execute the loop as long as the condition is true. The former checks the condition before each pass of the loop, while the latter checks the condition after each pass of the loop.

0 is a false value.

1 and other numbers are true values.

while (0) { ... } is useless. It's a loop that will never be executed.

while (1) { ... } is a infinite loop. Something like break , return or exit is needed to leave it.

do { ... } while (0); is a weird way of writing { ... } . [1]

do { ... } while (1); is a weird way of writing while (1) { ... } .


  1. do { ... } while (0) has use in macros .

in C all non zero values are the " true " and zero is " false ". So if the number is used as the logical expression it acts as the logical value of true or false . You can even use pointers as a logical values

char *ptr;
if(*ptr)
{
   //do something if ptr is not NULL 
}
else
{
   //do something if ptr is NULL 
}

The do {... } while(0) is used in the multi statement macros. Why?

Lets analyze the if statement:

if(condition)
    macro(x);
  else
   foo();

if the macro is just the simple compound statement like:

#define macro(x) {x *= 2; printf("%d\\n",x);} #define macro(x) {x *= 2; printf("%d\\n",x);} then the if statement will not compile

but if we define the macro this way:

#define macro(x) do{x *= 2; printf("%d\\n",x);}while(0)

everything is fine and syntactically OK.

You can test it yourself here: https://godbolt.org/z/RW7Zmo

do {...} while(0) will execute only once as the condition is checked after the statements inside the {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM