top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Which are the cases when should we use while(0) and while(1) in C?

+1 vote
753 views
Which are the cases when should we use while(0) and while(1) in C?
posted Jan 22, 2015 by anonymous

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

1 Answer

+1 vote

Well you can use while(1) whenever you wanted to run a set to code for infinite time.
example:

int main()
{
    while (1) {
        printf("I am always here :)\n");
    }
    return 0;
} 

The above code will print "I am always here :)" for infinite number to times.
You can use while (1) in client server program. Where server run in a while loop to receive any packet send form the client.
But its not advisable to use while (1) in realworld because it will increase the CPU usage and also block the code. i.e you can't come out from the while (1) untill you have to close the program manually.

while(0) : basically you won't find any example using while (0) except in do { } while (0); case.

while(0) {
  //some statement
}

while(0) will be always false hence the code inside while (0) would not executed.
you can use while(0) if you don't wanted the execute the code inside while loop.

Or you can use while(0) with do {} while(0);
for example:

int main()
{
     do {
         printf("Hello there!\n");
     } while (0);
     return 0;
}

It will print "Hello there!" only one time.

answer Jan 23, 2015 by Arshad Khan
Similar Questions
0 votes

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

+3 votes

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.

...