开发者

Strange behaviour for loop C++

开发者 https://www.devze.com 2023-04-10 20:57 出处:网络
I am havin开发者_运维百科g trouble understanding why in this code snippet the \"Hello\" statement is not

I am havin开发者_运维百科g trouble understanding why in this code snippet the "Hello" statement is not being printed. I thought that the condition statement in the for loop starts getting tested after only at the second iteration.

  for ( count = 0; count < 0; ++count)
    {
  cout<<"Hello!\n";     
    }


It never enters the loop at all because for loops are tested at the start.

You start with count = 0, but the loop condition is count < 0. So it fails right away and skips the entire loop.

do-while loops are the ones that are tested at the end of the iteration.


The for loop:

for (count = 0; count < 0; ++count)
{
    cout<<"Hello!\n";     
}

is defined to be equivalent to:

{
    count = 0;
    while (count < 0)
    {
        {
            cout<<"Hello!\n";
        }
        ++count;
    }
}

with the caveat that continue will go to ++count, rather than count < 0.


I thought that the condition statement in the for loop starts getting tested after only at the second iteration

No it does not. It is already checked before the first iteration.


The condition is tested first.

A for loop

 for (<initializer>; <condition>; <increment>) { <body> }

is equivalent to:

{
  <initializer>
  bool __first = true;
  while ((__first ? __first = false : (<increment>, true)), <condition>) {
    <body>
  }
}

The only looping construct that always iterates once is:

do {
  <body>
} while (<condition>);
0

精彩评论

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