Blocks in Programming: Units of Scope and Execution
In programming theory, a block is a piece of code that stands as a unit. Often enough, variables in a block are invisible or inaccessible to other blocks.
Blocks are often denoted by curly braces:
{ var x = 3; var y = x + 2; } { print(x); // ERROR: X has not been declared in this block }
The visibility of a variable is called its scope. In the code above, print(x);
fails to compile because x is out of scope
.
By the by, an enclosed block shares the variables in the enclosing scope:
{ var x = 3; var y = x + 2; { print(x); // OK } }
Blocks are good for organizing code into sections.
Two languages where blocks behave as decribed here are: