user3158491
user3158491

Reputation: 45

Why does my for loop in C# need a semicolon in the condition?

for (int frame <= 10; frame++)
{
}

For example, I have this code, but it is not working. When I put in a semi colon though, it works. Why is this?

for (; frame <= 10; frame++)
{
}

Upvotes: 0

Views: 1135

Answers (5)

Kevan
Kevan

Reputation: 129

I think your for loop (2nd example) works because you already initialize the variable frame before your for loop start.

for example:

int frame = 0;
for(; frame <= 10; frame++)
{

}

Upvotes: 2

canhazbits
canhazbits

Reputation: 1714

C# syntax dictates that the for statement has:

1) An initializer

2) A condition

3) An iterator

You don't have to put anything in those sections, but they still need to be there for the sake of the compiler.

See http://msdn.microsoft.com/en-us/library/ch45axte.aspx

Edit: As an aside, you could use a while loop instead:

while (frame++ <= 10)
{
  ...
}

Upvotes: 5

vmg
vmg

Reputation: 10576

because it is the language syntax http://msdn.microsoft.com/en-us/library/ch45axte.aspx

for (initializer; condition; iterator)
    body

Upvotes: 1

T McKeown
T McKeown

Reputation: 12857

Because the for loop's first part is the declaration/initialization, it is optional. Putting the ; just moves to the next part, the condition.

Upvotes: 0

Alexandre Rondeau
Alexandre Rondeau

Reputation: 2687

That is how the for works. It has three parts

From msdn documentation:

for (initializer; condition; iterator)
    body

basically, by putting an extra semicolon, you are giving it a empty initializer part.

Upvotes: 1

Related Questions