Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax of a for-loop without braces?

Tags:

syntax

c#

for (int y = 0; y < GameBoard.GameBoardHeight; y++)
        for (int x = 0; x < GameBoard.GameBoardWidth; x++)
        {
            if (GetSquare(x, y) == "Empty")
            {
                 RandomPiece(x, y);
            }
        }

The first for loop has no braces, and the next line is not even a statement with a ;. It's just a for loop.

Whats up with this?

like image 664
Thomas Avatar asked Jul 20 '12 05:07

Thomas


Video Answer


1 Answers

MSDN: The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false.

The main point to understand is the executes a statement or a block of statements part. The nested for in you example is a statement which contains a block of statements because of the { } pair.

So, if you wrote the above as only a single statement per nested operation, you will write:

for (int y = 0; y < GameBoard.GameBoardHeight; y++)
    for (int x = 0; x < GameBoard.GameBoardWidth; x++)
        if (GetSquare(x, y) == "Empty")
            RandomPiece(x, y);

or as a block statements per nested operation:

for (int y = 0; y < GameBoard.GameBoardHeight; y++)
{
    for (int x = 0; x < GameBoard.GameBoardWidth; x++)
    {
        if (GetSquare(x, y) == "Empty")
        {
            RandomPiece(x, y);
        }
    }
}
like image 199
Yogesh Avatar answered Oct 24 '22 19:10

Yogesh