Owais Qureshi
Owais Qureshi

Reputation: 43

What is output of this program and why?

#include <stdlib.h>
#include <stdio.h>
enum {false, true};
int main()
{
   int i = 1;
   do
   {
      printf("%d\n", i);
      i++;
      if (i < 15){
         continue;
      }
   } while (false);
   return 0;
}

Output

1

I don't understand why the output is 1, my assumption is that it because after first iteration it skip all other but how and why ?

Upvotes: 0

Views: 110

Answers (2)

kaylum
kaylum

Reputation: 14044

You may be expecting the continue to go back to the "top" of the loop at the do statement. But it actually goes to the end of the loop body. Which in the case of a do/while loop is the conditional check in the while.

The relevant section from the C standard which explains this:

A continue statement causes a jump to the loop-continuation portion of the smallest enclosing iteration statement; that is, to the end of the loop body. More precisely, in each of the statements

while (/* ... */) {
      /* ... */
      continue;
      /* ... */
contin: ;
}

do {
    /* ... */
    continue;
   /* ... */
contin: ;
} while (/* ... */);

for (/* ... */) {
    /* ... */
    continue;
   /* ... */
contin: ;
}

unless the continue statement shown is in an enclosed iteration statement (in which case it is interpreted within that statement), it is equivalent to goto contin;

So specifically for your code example the continue will result in a jump to while (false) on the first iteration which will terminate the loop.

Upvotes: 4

Kundan
Kundan

Reputation: 1962

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop.

A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.

do {
   statement(s);
} while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false.

And in your case the condition is false that's why the code inside do...while loop executed once.

Upvotes: 2

Related Questions