smilingbuddha
smilingbuddha

Reputation: 14660

Strange behaviour for loop C++

I am having 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";     
    }

Upvotes: 0

Views: 232

Answers (4)

Mankarse
Mankarse

Reputation: 40613

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.

Upvotes: 4

Matthieu M.
Matthieu M.

Reputation: 299740

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>);

Upvotes: 2

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76778

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.

Upvotes: 2

Mysticial
Mysticial

Reputation: 471199

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.

Upvotes: 7

Related Questions