Programming Search⌘K

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())
Output
('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: begin and end in ALGOL and Pascal, do and end in 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

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the blocks of JavaScript, with let and const scoped to the block and var scoped to the function. No example file exists.
GoNative
RustNative
KotlinNativeKotlin 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.
SQLNativeProcedural 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.
BashNative{ ...; } 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.
PowerShellNativeA 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.
HTMLDoes not applyHTML has no statements. A block element is a term of layout, not a group of statements.
CSSIdiomA rule has a declaration block in braces after its selector, and nested rules put a block inside a block.
Regular expressionsDoes not applyA 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.

PythonGitHub
# 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
Output
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 sq and n stay after the loop. A comprehension has its own scope, so k does not leak. with calls __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 needs pass.
#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";
}
Output
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 b closes before a. An if with an init-statement keeps it local to the if. A scoped_lock holds the mutex until the end of its block. A lambda that is called at once gives a value from a block.
JavaGitHub
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);
    }
}
Output
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. try with resources closes the resource at the end of the block. An arm of a switch expression can be a block that gives its value with yield. 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;
}
Output
inner x = 2
outer x = 1
sum = 10
calls = 1
*p = 7
  • Verdict: native. A compound statement is a block, and an inner x hides the outer one. The i of a for loop is local to the loop. Without braces, an if controls only the next statement, so the second hello() runs although its indent says otherwise. A static object 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}");
}
Output
y = 2
in the block
disposed a
after the block
unchecked: -2147483648
checked: OverflowException
n1
  • Verdict: native. A block makes a scope for y. A using declaration disposes the resource at the end of its block, so disposed a comes before after the block. checked and unchecked blocks choose what an overflow does. A lambda can have a block body.
JavaScriptGitHub
// 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);

Output
undefined 2
in the block
[ 0, 1, 2 ]
undefined
  • Verdict: native. let is scoped to the block and var to the function, so a is undefined after the block and b is 2. A labeled block can be left with break. A for loop with let makes a new binding for each iteration. After =>, a { starts a block, so value: is a label and the function returns undefined.
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")
}
Output
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 new x that hides the outer one. An if and each switch case are implicit blocks, so v and msg are local to them. defer runs when the function returns, not at the end of the loop body, and the deferred calls run in reverse order.
RustGitHub
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:?}");
}
Output
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 break with a value. A semicolon after the last expression makes the value of the block ().
  • 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, a for or a switch, and each case, can be a block of its own. Go defines this in its spec6, and C++ allows an init-statement in if and switch.
  • Labeled blocks. Java, JavaScript and Rust let a program leave a labeled block early with break. In Rust the break can 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 if controls only the next statement. A second line with the same indent looks like a part of the if, but it runs each time. Many style guides require braces for each if and loop.
  • A name that leaks from a block. In Python, and with var in 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 static object, an object on the heap or a value that is copied out.
  • defer is not a block exit. In Go, defer in 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 returns undefined. 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

  1. Block (programming), Wikipedia, Introduction; History; Syntax
  2. Statements, C reference, cppreference.com, Compound statements
  3. The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.2 Blocks
  4. Compound statements, The Python Language Reference, 8. Compound statements
  5. The Java Language Specification, Java SE 25 Edition, Chapter 6, 6.3 Scope of a Declaration; 6.4 Shadowing and Obscuring
  6. The Go Programming Language Specification, Blocks
  7. Execution model, The Python Language Reference, 4.1 Structure of a program
  8. Block statement, MDN Web Docs, Description
  9. Block expressions, The Rust Reference, expr.block.intro; expr.block.value-trailing-expr
  10. RAII, C++ reference, cppreference.com, Introduction
  11. Destructors, The Rust Reference, destructors.scope.intro
  12. using statement, C# language reference, using declaration
  13. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/7RQNNB/text.yaml