Conceptcore
Block
Also called block, code block, compound statement, block statement, suite, block scope, block structure, block expression, labeled block, begin end, curly braces, off-side rule.
A block is a group of statements that the language treats as one statement. In most languages a block is also a scope, so the names declared in it are local to it.
- Applies to
- core-languages
Idea
An if or a loop controls one statement, but the work often needs many statements. A block groups many statements into one, so a control structure can control all of them. Most languages mark a block with braces, some with begin and end, and Python with indentation. In most languages a block is also a scope: a name declared in the block is not visible outside it, and in some languages an object made in the block is destroyed at its end.
# Python groups statements into a block by indentation.
def classify(n):
if n < 0:
kind = "negative" # these two lines are one block
n = -n
else:
kind = "not negative"
return kind, n
print(classify(-4), classify(3))
# A block in Python is not a scope: a name made in the if block is visible after it.
if True:
made_inside = 42
print("made_inside =", made_inside)
# The loop variable also stays after the loop.
for i in range(3):
pass
print("i after the loop =", i)
# A function body is a scope, so a name made there is not visible outside.
def f():
local = 1
return local
f()
print("local" in globals())
('negative', 4) ('not negative', 3)
made_inside = 42
i after the loop = 2
False
The two indented lines after if n < 0: are one block, so both run when the condition is true. Python is different from most languages in one way: an if block or a loop body is not a scope. made_inside and the loop variable i stay visible after their blocks. Only a module, a function body and a class body make a new scope, so local is not visible outside f.
How it works
A group of statements. "A block of source code is a grouping of statements that execute in sequential order, top to bottom", and "Syntactically, a block acts much like a single statement"1. The grammar of most languages says that an if, a while or a for controls one statement, and a block is one statement. C calls it a compound statement: "A compound statement, or block, is a brace-enclosed sequence of statements and declarations"2.
How the block is marked.
- Braces: C, C++, Java, C#, JavaScript, Go and Rust. The Java grammar is
Block: { [ BlockStatements ] }3. - Keywords:
beginandendin ALGOL and Pascal,doandendin Ruby and Lua. - Indentation: "Python and Haskell use indentation to demarcate a block instead of delimiters as most languages do"1. Python calls the block a suite: "A suite is a group of statements controlled by a clause", and it can be on the same line as the header or on indented lines after it4.
A block is a scope. In most languages a name that a block declares is local to the block. In Java, the scope of a local variable "is the rest of the block, starting with the declaration's own initializer"5. Go has explicit blocks and implicit ones: "Each "if", "for", and "switch" statement is considered to be in its own implicit block"6, so a variable declared in the header of an if is local to the if. See lexical scope.
Where blocks are not scopes. In Python, "A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition"7. An indented suite is not in this list, so it is not a scope. In JavaScript, let, const and class are scoped to the block, but var and function declarations in non-strict mode "do not have block scope"8.
Hiding a name. An inner block can usually declare a name that the outer block has, and the inner name hides the outer one. C, C++, Go and Rust allow this. Java and C# do not allow it for local variables: "It is a compile-time error if the name of a local variable v is used to declare a new variable within the scope of v"5.
A block as an expression. In Rust, "A block expression, or block, is a control flow expression and anonymous namespace scope for items and variable declarations", and "When a block contains a final operand, the block has the type and value of that final operand"9. So let area = { let w = 3; let h = 4; w * h }; gives 12. A semicolon after the last expression makes the value (). Java has a similar form: an arm of a switch expression can be a block that ends with yield.
The end of a block. In C++, C# and Rust, the end of a block is also the end of the life of its local objects. C++ uses this for RAII, which "binds the life cycle of a resource that must be acquired before use ... to the lifetime of an object"10. In Rust, "When control flow leaves a drop scope all variables associated to that scope are dropped in reverse order of declaration"11. In C#, with a using declaration, "a local variable is disposed at the end of the scope in which it's declared"12.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the blocks of JavaScript, with let and const scoped to the block and var scoped to the function. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin marks blocks with braces, and a lambda block gives the value of its last expression, which run, use and other scope functions use. No example file exists because kotlinc is not installed. |
| SQL | Native | Procedural SQL such as PL/pgSQL and T-SQL groups statements with BEGIN and END, and a block can declare its own variables. No example file exists. |
| Bash | Native | { ...; } groups commands in the current shell, and ( ... ) runs them in a subshell, so a variable set in it is lost. A block is not a scope: local works only in a function. No example file exists. |
| PowerShell | Native | A script block in braces groups statements and is also a value that the program can store and call with the & operator. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no statements. A block element is a term of layout, not a group of statements. |
| CSS | Idiom | A rule has a declaration block in braces after its selector, and nested rules put a block inside a block. |
| Regular expressions | Does not apply | A group joins parts of a pattern, but a pattern has no statements to put in a block. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | indented suites; a suite is not a scope |
| JavaScript | native | { }; let and const are block scoped, var is not; labeled blocks |
| TypeScript | native | as JavaScript |
| Java | native | { }; labeled blocks; initializer blocks; a local cannot hide a local |
| Kotlin | native | { }; a lambda block gives the value of its last expression |
| C# | native | { }; using declarations; checked and unchecked blocks |
| Go | native | { }; implicit blocks for if, for, switch and each case |
| Rust | native | block expressions with a value; labeled blocks; drop at the end of a block |
| C | native | compound statements; block scope; automatic storage |
| C++ | native | compound statements; destructors at the end of a block (RAII) |
| Bash | native | { ...; } groups commands; ( ... ) runs them in a subshell |
| PowerShell | native | script blocks { }, which are also values |
| SQL | native | BEGIN ... END in procedural SQL |
| Regex | n/a | groups group parts of a pattern, but a pattern has no statements |
| HTML | n/a | no statements; a block element is a layout term |
| CSS | idiom | a rule has a declaration block in { } |
Every general-purpose language has blocks, so the verdict is native. The languages differ in how they mark a block, in whether a block is a scope, in whether a block has a value, and in what happens to the local objects at the end of the block.
The example files show these differences. Python shows that the names from a loop body stay after the loop, that a comprehension has its own scope, and that with runs exit code at the end of its block. JavaScript shows let and var in a block, a labeled block, a let binding per loop iteration, and a { after => that starts a block and not an object. Java shows a static initializer block, a labeled block, try with resources and a block in a switch arm. C# shows a using declaration and checked and unchecked blocks. Go shows a name in an inner block, the implicit block of an if and defer, which runs at the end of the function and not at the end of the block. Rust shows a block with a value, a drop at the end of a block and a labeled block with break. C shows a name that hides an outer name, an if without braces and a static local. C++ shows destructors at the end of a block, an if with an init-statement and a lock that the block holds.
# A compound statement has a header and a suite; the suite is the block.
total = 0
for n in range(1, 4):
sq = n * n
total += sq
print("total =", total, "sq =", sq) # the names from the loop body stay
# A comprehension has its own scope, so its variable does not leak.
squares = [k * k for k in range(3)]
print("squares =", squares, "k" in globals())
# with is a block whose exit code runs even after an exception.
class Tracker:
def __enter__(self):
print("enter")
return self
def __exit__(self, kind, value, tb):
print("exit", kind.__name__ if kind else None)
return True # suppress the exception
with Tracker():
raise ValueError("inside")
print("after with")
# An empty block needs pass, because a suite cannot be empty.
if total > 0:
pass
total = 14 sq = 9
squares = [0, 1, 4] False
enter
exit ValueError
after with
- Verdict: native. A suite is the block of a compound statement, and it is not a scope, so
sqandnstay after the loop. A comprehension has its own scope, sokdoes not leak.withcalls__exit__at the end of its block, also after an exception, and here__exit__suppresses the exception. A suite cannot be empty, so an empty block needspass.
#include <iostream>
#include <map>
#include <mutex>
#include <string>
struct Guard {
std::string name;
explicit Guard(std::string n) : name(std::move(n)) { std::cout << "open " << name << "\n"; }
~Guard() { std::cout << "close " << name << "\n"; }
};
int main() {
{ // a destructor runs at the end of the block (RAII)
Guard a("a");
Guard b("b");
std::cout << "in the block\n";
} // b is destroyed first, then a
// An if with an init-statement: it is local to the if and its else.
std::map<std::string, int> ages{{"ada", 36}};
if (auto it = ages.find("ada"); it != ages.end()) {
std::cout << "ada is " << it->second << "\n";
}
// A lock is held until the end of the block.
std::mutex m;
int shared = 0;
{
std::scoped_lock lock(m);
shared += 1;
}
std::cout << "shared = " << shared << "\n";
// A lambda body is a block, and an immediately called lambda gives a value.
const int limit = [] {
int v = 2;
v *= 21;
return v;
}();
std::cout << "limit = " << limit << "\n";
}
open a
open b
in the block
close b
close a
ada is 36
shared = 1
limit = 42
- Verdict: native. Destructors run at the end of a block in reverse order of construction, so
bcloses beforea. Anifwith an init-statement keepsitlocal to theif. Ascoped_lockholds the mutex until the end of its block. A lambda that is called at once gives a value from a block.
public class Main {
static int count;
// A static initializer block runs once, when the class is initialized.
static {
count = 10;
}
public static void main(String[] args) {
int x = 1;
{
int y = x + 1; // y is local to this block
System.out.println("y = " + y);
}
// int x = 5; in the block above would not compile, because a local cannot hide a local
// A labeled block can be left with break.
found: {
for (int i = 0; i < 5; i++) {
if (i * i > 6) {
System.out.println("first i with i*i > 6: " + i);
break found;
}
}
System.out.println("not found");
}
// try-with-resources closes the resource at the end of the block.
try (AutoCloseable r = () -> System.out.println("closed")) {
System.out.println("in try, count = " + count);
} catch (Exception e) {
System.out.println(e);
}
// A switch expression arm can be a block that yields a value.
String s = switch (x) {
case 1 -> {
String t = "one";
yield t.toUpperCase();
}
default -> "other";
};
System.out.println("s = " + s);
}
}
y = 2
first i with i*i > 6: 3
in try, count = 10
closed
s = ONE
- Verdict: native. A static initializer block runs once when the class is initialized. A labeled block can be left with
break.trywith resources closes the resource at the end of the block. An arm of aswitchexpression can be a block that gives its value withyield. A local variable cannot hide another local variable.
#include <stdio.h>
static int calls;
static void hello(void) { calls++; }
int main(void) {
int x = 1;
{ /* a compound statement is a block */
int x = 2; /* this x hides the outer x */
printf("inner x = %d\n", x);
}
printf("outer x = %d\n", x);
/* A for statement is a block, so i is not visible after the loop. */
int sum = 0;
for (int i = 1; i <= 4; i++) sum += i;
printf("sum = %d\n", sum);
/* Without braces, only the first statement belongs to the if. */
if (x > 5)
hello();
hello(); /* this call is outside the if, although the indent says otherwise */
printf("calls = %d\n", calls);
/* An automatic object lives until the end of its block. */
int *p;
{
static int kept = 7; /* static storage: it lives for the whole program */
p = &kept;
}
printf("*p = %d\n", *p);
return 0;
}
inner x = 2
outer x = 1
sum = 10
calls = 1
*p = 7
- Verdict: native. A compound statement is a block, and an inner
xhides the outer one. Theiof aforloop is local to the loop. Without braces, anifcontrols only the next statement, so the secondhello()runs although its indent says otherwise. Astaticobject in a block lives for the whole program.
int x = 1;
{
int y = x + 1; // y is local to this block
Console.WriteLine($"y = {y}");
}
// using declares a resource that is disposed at the end of the block.
{
using var r = new Resource("a");
Console.WriteLine("in the block");
}
Console.WriteLine("after the block");
// checked and unchecked are blocks that change the rules for overflow.
int big = int.MaxValue;
unchecked { Console.WriteLine($"unchecked: {big + 1}"); }
try { checked { Console.WriteLine(big + 1); } }
catch (OverflowException) { Console.WriteLine("checked: OverflowException"); }
// A lambda can have a block body with statements and a return.
Func<int, string> name = n => { var s = n.ToString(); return "n" + s; };
Console.WriteLine(name(x));
class Resource(string id) : IDisposable
{
public void Dispose() => Console.WriteLine($"disposed {id}");
}
y = 2
in the block
disposed a
after the block
unchecked: -2147483648
checked: OverflowException
n1
- Verdict: native. A block makes a scope for
y. Ausingdeclaration disposes the resource at the end of its block, sodisposed acomes beforeafter the block.checkedanduncheckedblocks choose what an overflow does. A lambda can have a block body.
// let and const are scoped to the block; var is scoped to the function.
{
let a = 1;
var b = 2;
}
console.log(typeof a, b);
// A labeled block can be left early with break.
outer: {
console.log("in the block");
if (b === 2) break outer;
console.log("not printed");
}
// Each iteration of a for loop with let has its own binding.
const fs = [];
for (let i = 0; i < 3; i++) { fs.push(() => i); }
console.log(fs.map((f) => f()));
// After =>, a { starts a block, so value: is a label and the function returns undefined.
const r = (() => { value: 1 })();
console.log(r);
undefined 2
in the block
[ 0, 1, 2 ]
undefined
- Verdict: native.
letis scoped to the block andvarto the function, soais undefined after the block andbis2. A labeled block can be left withbreak. Aforloop withletmakes a new binding for each iteration. After=>, a{starts a block, sovalue:is a label and the function returnsundefined.
package main
import "fmt"
func main() {
x := 1
{
x := 2 // a new x in the inner block hides the outer one
y := x * 10
fmt.Println("inner x =", x, "y =", y)
}
fmt.Println("outer x =", x)
// The if statement is an implicit block, so v is visible only in it.
if v := x + 5; v > 3 {
fmt.Println("v =", v)
}
// Each case of a switch is an implicit block.
switch x {
case 1:
msg := "one"
fmt.Println(msg)
default:
msg := "other"
fmt.Println(msg)
}
// defer runs at the end of the function, not at the end of the block.
for i := range 2 {
defer fmt.Println("deferred", i)
}
fmt.Println("end of main")
}
inner x = 2 y = 20
outer x = 1
v = 6
one
end of main
deferred 1
deferred 0
- Verdict: native. A
:=in an inner block declares a newxthat hides the outer one. Anifand eachswitchcase are implicit blocks, sovandmsgare local to them.deferruns when the function returns, not at the end of the loop body, and the deferred calls run in reverse order.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) { println!("drop {}", self.0); }
}
fn plus_one(x: i32) -> i32 { x + 1 }
fn main() {
// A block is an expression: its value is the value of its last expression.
let area = {
let w = 3;
let h = 4;
w * h
};
println!("area = {area}");
// A value is dropped at the end of the block that owns it.
{
let _a = Noisy("a");
println!("in the block");
}
println!("after the block");
// A labeled block can break with a value.
let first = 'search: {
for n in [3, 8, 12] {
if n % 4 == 0 { break 'search n; }
}
0
};
println!("first multiple of 4 = {first}");
// A semicolon after the last expression makes the value ().
let unit = { plus_one(area); };
println!("unit = {unit:?}");
}
area = 12
in the block
drop a
after the block
first multiple of 4 = 8
unit = ()
- Verdict: native. A block is an expression, and its value is the value of its final operand. A value is dropped at the end of the block that owns it. A labeled block can
breakwith a value. A semicolon after the last expression makes the value of the block().
Variations and related ideas
- Block structure. A language where blocks nest and each block can declare names is block-structured. ALGOL 60 started this13. See structured programming.
- Implicit blocks. The header of an
if, aforor aswitch, and each case, can be a block of its own. Go defines this in its spec6, and C++ allows an init-statement inifandswitch. - Labeled blocks. Java, JavaScript and Rust let a program leave a labeled block early with
break. In Rust thebreakcan carry the value of the block. - Blocks as values. A lambda or a closure is a block that the program can store and call later. Smalltalk and Ruby call them blocks, PowerShell has script blocks, and Kotlin passes a lambda block as the last argument.
- Statement expressions. GNU C has a non-standard
({ ... })form that makes a block into an expression. C++ uses a lambda that is called at once to get the same effect.
Pitfalls
- A missing pair of braces. Without braces, an
ifcontrols only the next statement. A second line with the same indent looks like a part of theif, but it runs each time. Many style guides require braces for eachifand loop. - A name that leaks from a block. In Python, and with
varin JavaScript, a name made in a block is still visible after it, and code that reads it later can get a stale value. - A name that hides another. In C, C++ and Go, an inner declaration with the same name hides the outer one, and an assignment changes the inner name only. In Go,
x, err := f()in an inner block is a common case. - A pointer to a dead object. In C and C++, a pointer to a local object of a block is not valid after the block ends. Use a
staticobject, an object on the heap or a value that is copied out. deferis not a block exit. In Go,deferin a loop runs when the function returns, not at the end of each iteration, so a loop that opens files can keep them all open.- An object literal that is a block. In JavaScript,
() => { value: 1 }is a function with a block and a label, and it returnsundefined. Write() => ({ value: 1 }).
Cost
A block itself costs nothing at run time. The compiler uses it to find the scope of each name and to reuse stack slots for names whose blocks do not overlap. The code at the end of a block can cost time: a destructor in C++, a drop in Rust, a Dispose call in C# or the exit method of a with in Python. This cost is usually the release of a resource that the program must release anyway.
History
"The block concept was developed in the 1950s during the development of the first autocodes", and "Algol 58 introduced the notion of the "compound statement", which was related solely to control flow"1. The ALGOL 60 report added the block: "A sequence of declarations followed by a sequence of statements and enclosed between begin and end constitutes a block. Every declaration appears in a block in this way and is valid only for that block"13. It also said that "Every block automatically introduces a new level of nomenclature"13.
Later languages kept the block and changed its marks. C used braces2. Python used indentation4. C++ joined the end of a block to the release of resources10, and Rust made the block an expression with a value9.
References
- Block (programming), Wikipedia, Introduction; History; Syntax
- Statements, C reference, cppreference.com, Compound statements
- The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.2 Blocks
- Compound statements, The Python Language Reference, 8. Compound statements
- The Java Language Specification, Java SE 25 Edition, Chapter 6, 6.3 Scope of a Declaration; 6.4 Shadowing and Obscuring
- The Go Programming Language Specification, Blocks
- Execution model, The Python Language Reference, 4.1 Structure of a program
- Block statement, MDN Web Docs, Description
- Block expressions, The Rust Reference, expr.block.intro; expr.block.value-trailing-expr
- RAII, C++ reference, cppreference.com, Introduction
- Destructors, The Rust Reference, destructors.scope.intro
- using statement, C# language reference, using declaration
- Revised Report on the Algorithmic Language Algol 60, J. W. Backus and others, edited by Peter Naur, Description of the reference language; 4.1.3 Semantics
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 7RQNNB Edit this page History Report an error Markdown