top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the use of while(0) statement in C?

+3 votes
870 views

While(0) means dont enter into it, but why you want to have while(0) in c code. Any suggestion.

Asked in the interview today.

posted Oct 9, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

You are right. But some times while(0) (do ... while(0)) is used for error checking and to avoid deep nested if's.
Typical C Style coding as we dont have exception in C.

Example:
do {
// do something
if (error) {
break;
}
// do something else
if (error) {
break;
}
// etc..
} while (0);

answer Oct 9, 2014 by Pushkar K Mishra
0 votes

As Pushkar pointed out while(0){} is a null statement and is not used and even if you use compiler may optimize it. The only case is do..while(0) where one more possibility is the following (Credit: SO)

#define FOO(x) { foo(x); bar(x); }

Using this in an if statement would require that you omit the semicolon, which is counterintuitive:

if (condition)
    FOO(x)
else
    ...

If you define FOO like this:

#define FOO(x) do { foo(x); bar(x); } while (0)

then the following is syntactically correct:

if (condition)
    FOO(x);
else
    ....
answer Oct 9, 2014 by Salil Agrawal
Similar Questions
–1 vote
while(i<10);
{
  i++;
  printf("%d,\n", i);
}

Loop does not run for 10 iterations, what is the error?

0 votes

Lot of confusion and lot of scattered info, can someone help me by providing to the point response.

+2 votes
for (a=1; a&lt;=100; a++)

printf (&quot;%d\n&quot;, a * a);
...