GOOC - Game Oriented Object C

GOOC - Game Oriented Object C

Next: The if and unless Statements, Previous: Instruction Statements, Up: Statements
[Contents]

8.2. Blocks

8.2. Blocks

A block is a set of zero or more statements enclosed in braces. Often, a block is used as the body of an if or unless statement or a loop statement, to group statements together. if (x <= 0) { x += 400.0 }

Since a block is a statement that groups statements together, they can include other blocks. if (x <= 0) { if (x < 400.0) { x += 400.0 } }

You can declare variables inside a block; such variables are local to that block. It is common to introduce a block simply for the purpose of making the scope of a local variable more specific, due to limited stack space. { var foo = 15.0 + y if (x <= 0) { x += foo } } x = foo // compiler error, foo does not exist outside of the previous block.

Certain statements will always expect a block proceding them. If you only wish your block to have a single statement without having to write braces, simply append a semicolon ; after your statement. if (x <= 0) x += 400.0;

Since blocks can contain themselves, a series of blocks can be written by using these single-statement blocks. Therefore, the semicolon is actually completely optional and valid for almost every scenario bar the one described one, however single-instruction blocks cannot declare new variables. This type of syntax is therefore not recommended. x += 400.0; nop(); var foo = 15.0 + y; // error, single-instruction blocks cannot define new variables x = foo;