Can someone please explain what the line for(;Q.size();) does?

105 Views Asked by At

I am trying to understand a source code and i cannot figure out how the line for(;Q.size();) is meant to work. Could someone please simplify it for me ?

3

There are 3 best solutions below

0
On

It's a for loop which doesn't care about an incrementing index variable. As Blaze pointed out it's equivalent to a while loop.

for(;Q.size();)
{
   // do something while Q is not empty
}

or equivalently

while(Q.size())
{
   // do something while Q is not empty
}
0
On

Look at it this way:

for(<do nothing>;Q.size();<do nothing>) {//do something}

Now read the definition of the for loop and see that it fits perfectly. As mentioned by others, essentially this becomes equivalent to while(Q.size())

0
On

A for statement consists of three parts, separated by semicolons:

  • an init-statement
  • a condition
  • an iteration_expression

A for loop is equivalent to this code:

{
    init_statement 
    while ( condition ) { 
        statement 
        iteration_expression ; 
    }
}

The init-statement and iteration_expression can be empty, but the semicolons between them are still required.

In your example, for(;Q.size();) would thus be equivalent to:

{
    while ( Q.size() ) { 
        statement 
    }
}