Ballen Abdullah
Ballen Abdullah

Reputation: 25

I would like to know the reason for the terminal output for this code in an exam question for C

The code is taken from an exam question which I did not know the answer for:

int c = 0;

while (c < 5)
{
    if (c == 2)
    {
        continue;
    }

    printf ("data %d", ++c);
}

I know that it prints nothing, but I would like to know why?

Any help would be appreciated.

Upvotes: 1

Views: 89

Answers (3)

ProXicT
ProXicT

Reputation: 1933

By default, on POSIX systems, stdout is a buffered stream which will only flush when it hits a line feed or when it's explicitly asked to flush using fflush(stdout);

Add fflush(stdout); after the printf() call and then your program should output:

data 1data 2

After that, your program will be stuck in an infinite loop, because the condition in your while statement will always be evaluated to true.

Upvotes: 2

fugiefire
fugiefire

Reputation: 316

There are some buffering issues. If you add fflush(stdout) after the printf, you get data 1data 2. It doesn't go further than data2 because once c is equal to 2, it will keep hitting the if case and skipping the increment. Try the following and you will get data 1data 2:

int c = 0;

while (c < 5)
{
    if (c == 2)
    {
        continue;
    }
    printf ("data %d", ++c);
    fflush(stdout);
}

Upvotes: 1

Devon
Devon

Reputation: 160

Once c == 2 is true, then you will stay in the loop and keep hitting the if statement. So you'll never increment once c is set to 2.

int c = 2;
if(c == 2) {
    continue;
}
printf("%d", c); // this will never get hit once c is 2 since continue will 
//make the program jump to the next iteration of the loop.
//Also by not flushing after the print, you aren't clearing the buffer and are then not accepting the next print.

You don't need to fflush(stdout) if the infinite loop is fixed though.

Upvotes: 1

Related Questions