What means ';' inside of for statement?
-
10-02-2021 - |
Question
I'm trying to understand the follow code below:
/**
* Simple insertion sort.
* @param a an array of Comparable items.
*/
public static void insertionSort( Comparable [ ] a )
{
for( int p = 1; p < a.length; p++ )
{
Comparable tmp = a[ p ];
int j = p;
for( ; j > 0 && tmp.compareTo( a[j-1] ) < 0; j-- )
a[ j ] = a[ j - 1 ];
a[ j ] = tmp;
}
}
But i'm not sure what means for( ; )
so I need your help guys.
Sorry if it's duplicated but I search here and in Google but nothing so far.
Solution
The first part of a for loop is what happens before the looping begins. Usually it's used for assigning a variable.
The ";" with nothing (apart from the bracket) before it merely says "There's nothing I want doing before the start of the loop". No variable needs to be assigned, etc.
OTHER TIPS
It is simple: It basically means
for(..a.. ; ..bb.. ; ..c..){ // }.
..a.. : is what you initialize if any or leave it empty. ..b.. : Any check you want to carry once a loop is run once. ..c.. Any change to the variable after the loop is run once
I guess you're wandering about the second for loop syntax. It's just a regular for loop without any initialization part. j
must be declared before the loop because it's used outside, after the loop has ended.
It's just a separator. If there's nothing in front of it, that means that part of the logic is empty. The format is
for( <stuff to do before starting the loop>
;
<stuff to do before each iteration, and maybe give a value of 0 to terminate it>
;
<stuff to do at the end of each iteration>
)
Frankly I find it very flexible, because not every loop is of the form "do this for each xxx". What you put in each of those sections is really arbitrary.