Programming Fundamentals/Code Blocks

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Overview[edit]

A code block, sometimes referred to as a compound statement, is a lexical structure of source code which is grouped together. Blocks consist of one or more declarations and statements. A programming language that permits the creation of blocks, including blocks nested within other blocks, is called a block-structured programming language. Blocks are fundamental to structured programming, where control structures are formed from blocks.[1]

Discussion[edit]

The Need for a Compound Statement[edit]

Within many programming languages, there can be only one statement listed as the action part of a control structure:

if (expression)
    statement
else
    statement

Often, we will want to do more than one statement. This problem is overcome by creating a code block or compound statement. For programming languages that use curly braces {} to designate code blocks, a compound if-then-else statement would be similar to:

if(expression)
{
    statement;
    statement;
}
else
{
    statement;
    statement;
}

Because programmers often forget that they can have only one statement listed as the action part of a control structure; the programming industry encourages the use of indentation (to see the action parts clearly) and the use of compound statements (braces) always, even when there is only one statement. Thus:

if(expression)
{
    statement;
}
else
{
    statement;
}

By writing code in this manner, if the programmer modifies the code by adding more statements to either the action true or the action false; they will not introduce either compiler or logic errors. Using indentation and braces should become standard practice in any language that requires the use of compound statements with control structures.

Indentation and End Block[edit]

Other programming languages require explicit designation of code blocks through either indentation or some type of end block statement. For example, Python uses indentation to indicate the statements in a code block:

if expression:
    statement
    statement
else:
    statement
    statement

Lua uses an end block reserved word:

if expression then
    statement
    statement
else
    statement
    statement
end

The general if-then-else structure in each of these programming languages is similar, as is the required or expected indentation. The difference is in the syntax used to designate the code blocks.

Key Terms[edit]

block
Another name for a compound statement.
compound statement
A unit of code consisting of zero or more statements.

References[edit]