Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omit first parameter in for loop

In PHP, Java, C++ (and many other languages), for loops are used like this:

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

If I already initialized i, how can I omit the initialization statement?

like image 636
Leo Jiang Avatar asked Dec 07 '22 15:12

Leo Jiang


2 Answers

In Java, C++ and PHP it is completely valid to omit the initialization portion of the for loop

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

This is true of most languages which have a for loop structure

like image 70
JaredPar Avatar answered Dec 10 '22 11:12

JaredPar


for(; i < 10; i++) {
    ...
}

You can leave out any of the items in the for loop if they are not needed. You could also put in multiple things to do, or multiple conditions to check such as:

int j = 40;
for(int i = 0; i < 10 || j > 30; i++, j--) {}
like image 38
Collin Avatar answered Dec 10 '22 13:12

Collin