Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 443
nunos Avatar asked Dec 28 '09 20:12

nunos


2 Answers

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
}
like image 135
Pace Avatar answered Sep 22 '22 03:09

Pace


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
}
like image 45
cyborg Avatar answered Sep 22 '22 03:09

cyborg