Amirpr
Amirpr

Reputation: 9

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");
}

Upvotes: 0

Views: 179

Answers (2)

ikegami
ikegami

Reputation: 385789

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.

Upvotes: 4

0___________
0___________

Reputation: 67476

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);} 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 {}

Upvotes: 1

Related Questions