xhtml
 

Blocks

A series of statements surrounded by curly brackets is called a block. This effectively turns the whole group of statements into a single statement. Anywhere in a program that you can put a single statement, you can put a block instead (and in most places that you can put a block, you can put a single statement instead).

Any variable declared inside a block is a local variable, that is a temporary one which only lasts for the duration of the block, and is not visible outside it. For example, you can swap the values of two variables like this:

int m = 23;
int n = 45;
{
   int temp = n;
   n = m;
   m = temp;
}

The local variable temp won't be visible outside the little block, and won't get mixed up with any other variable called temp anywhere else in the program.

If you need to calculate something inside a block and then have it available after the block ends, you need to declare the variable before the block starts. For example, this fails:

{
   int n = 41;
}
n = n + 1;

but this succeeds:

int n;
{
   n = 41;
}
n = n + 1;

Back