-2

I was following a tutorial for how to make an insertion sort and came across this line of code:

for(; j >= 0 && tempVar < insertionArray[j]; j--)

My question is, what does the single semicolon mean after the first bracket?

I know that a double semicolon in a for loop defines an infinite loop,

for(;;)

but what does a single one mean?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Wzrd
  • 238
  • 1
  • 4
  • 16
  • 1
    The same as [in other languages like C++ or C](https://stackoverflow.com/questions/16113125/two-semicolons-inside-a-for-loop-parentheses). – Uwe Keim Apr 28 '19 at 11:06
  • It means one does not declare and assign counter `j` in the loop, but it should be done somewhere else before the loop. – CSDev Apr 28 '19 at 11:06
  • https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/for – chadnt Apr 28 '19 at 11:08

4 Answers4

1

There are 3 parts to a for loop, each separated by semicolons:

      initialisation;   evaluation  ;  iteration  
for (   int i = 0   ; i < someValue ;     i++    )

If you have already initialized the variable that you want to evaluate and iterate through, you don't need to do it in the loop:

int i = 0;

for(; i < someValue ; i++ )
zing
  • 561
  • 3
  • 12
0

The first part of a for loop is to declare and initialize the counter variable (j in this case). Since it was declared and initialized before the loop, we don't do it again.

Albert
  • 487
  • 1
  • 4
  • 16
0

It divides the line into different blocks.

The first part is one time statement, the second is the condition of the loop and the third is a operation to do after/before the loop's code.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

This just the initializer section The statements in the initializer section are executed only once, before entering the loop. The initializer section is either of the following:

The declaration and initialization of a local loop variable, which can't be accessed from outside the loop.

Zero or more statement expressions from the following list, separated by commas:

assignment statement

invocation of a method

prefix or postfix increment expression, such as ++i or i++

prefix or postfix decrement expression, such as --i or i--

creation of an object by using new keyword

await expression

evilGenius
  • 1,041
  • 1
  • 7
  • 16