tags:

views:

163

answers:

2

Hi there, anyone can explain me, why this parts of code are acting differently?

while((c = fread(buf, sizeof(char), 1, f)) != 0);
{
    if(write(t, buf, c) < 0)
    {
        return E_MSGSEND;
    }
}

/////////////////////////////////////

do
{
    c = fread(buf, sizeof(char), 1, f);
    if(write(t, buf, c) < 0) 
    {
            return E_MSGSEND;
    }
} while(c != 0);

while {} runs only 1time but do {} while 5times. Whats is the difference? Before while {} c is intialized to 1.

Thanks an advice

+23  A: 

You have a semicolon after your first while:

while((c = fread(buf, sizeof(char), 1, f)) != 0);

This in effect makes it an empty loop, which may well execute the same amount of times as the other loop, but its body doesn't include any statements. The following if, though, is not part of that loop anymore, so it only executes once.

Péter Török
Haha, I was about to post about the semantic differences in the two blocks like everyone else did. Good catch, +1
Tanzelax
+1. @Jay: To avoid bugs like this going forward, compile at a higher compiler warning level.
jdv
+1 Oops, crossed eyes. LOL
madatanic
+1. Good catch!
Justin Ethier
I should visit some market and watch for new pair of eyes. Thanks a lot. Omg, sorry
Jay Gridley
@Jay Welcome :-) Don't make too much of a problem out of it, I believe all of us (including myself) have had similar omissions (or worse). May I ask you to check the answer as "accepted" once you verified that it solved your problem? Thanks :-)
Péter Török
A: 

In the first section, using the while loop, you check for EOF or successful read before executing the inner statements.

In the second section, using the do-while loop, you don't check for EOF before executing the if statement.

Thomas Matthews