nunos
nunos

Reputation: 21389

What does it mean when the first "for" parameter is blank?

I have been looking through some code and I have seen several examples where the first element of a for cycle is omitted.

An example:

for ( ; hole*2 <= currentSize; hole = child)

What does this mean?

Thanks.

Upvotes: 7

Views: 12530

Answers (8)

user230821
user230821

Reputation: 1123

Some people have been getting it wrong so I just wanted to clear it up.

int i = 0;
for (; i < 10; i++)

is not the same as

for (int i = 0; i < 10; i++)

Variables declared inside the for keyword are only valid in that scope.

To put it simply.

Valid ("i" was declared outside of the loops scope)

int i = 0;
for (; i < 10; i++)
{
  //Code
}
std::cout << i;

InValid ("i" does not exist outside the loop scope)

for (int i = 0; i < 10; i++)
{
  //Code
}
std::cout << i;

Upvotes: 3

Pace
Pace

Reputation: 43817

It just means that the user chose not to set a variable to their own starting value.

for(int i = 0; i < x; i++)

is equivalent to...

int i = 0;
for( ; i < x; i++)

EDIT (in response to comments): These aren't exactly equivalent. the scope of the variable i is different.

Sometimes the latter is used to break up the code. You can also drop out the third statement if your indexing variable is modified within the for loop itself...

int i = 0;
for(; i < x;)
{
...
i++
...
}

And if you drop out the second statement then you have an infinite loop.

for(;;)
{
runs indefinitely
}

Upvotes: 25

codaddict
codaddict

Reputation: 455132

Suppose you wanted to

for (hole=1 ; hole*2 <= currentSize; hole = child)

But the value of hole just before the for loop was already 1, then you can slip this initilization part of the loop:

/* value of hole now is 1.*/
for ( ; hole*2 <= currentSize; hole = child)

Upvotes: 1

Michal Sznajder
Michal Sznajder

Reputation: 9406

It means that the initial value of hole was set before we got to the loop.

Looks like a list traversal of some kind.

Upvotes: 1

cyborg
cyborg

Reputation: 5748

The for construct is basically ( pre-loop initialisation; loop termination test; end of loop iteration), so this just means there is no initialisation of anything in this for loop.

You could refactor any for loop thusly:

pre-loop initialisation
while (loop termination test) {
...
end of loop iteration
}

Upvotes: 8

Alan Alvarez
Alan Alvarez

Reputation: 253

You could omit any of the parameters of a for loop. ie: for(;;) {} is about the same as while(true) {}

Upvotes: 1

Ashish
Ashish

Reputation: 8529

That means loop control variable is initialized before the for loop .

For C  code,

int i=0;
for( ; i <10 ; i++) { } //since it does not allow variable declaration in loop 

For C++  code,

for(int i=0 ; i <10 ; i++) { }  

Upvotes: 1

John Knoeller
John Knoeller

Reputation: 34148

It means that the initial value of hole was set before we got to the loop

Upvotes: 2

Related Questions