开发者

C++ weird thing

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

while((c = fre开发者_如何学Cad(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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜