HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, a block or code block or block of code is a lexical structure of
source code In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the wo ...
which is grouped together. Blocks consist of one or more declarations and
statements Statement or statements may refer to: Common uses *Statement (computer science), the smallest standalone element of an imperative programming language *Statement (logic), declarative sentence that is either true or false *Statement, a declarative ...
. A
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
that permits the creation of blocks, including blocks
nested ''Nested'' is the seventh studio album by Bronx-born singer, songwriter and pianist Laura Nyro, released in 1978 on Columbia Records. Following on from her extensive tour to promote 1976's ''Smile'', which resulted in the 1977 live album ''Season ...
within other blocks, is called a block-structured programming language. Blocks are fundamental to
structured programming Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of the structured control flow constructs of selection ( if/then/else) and repetition ( ...
, where
control structure In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imper ...
s are formed from blocks. Blocks have two functions: to group statements so that they can be treated as one statement, and to define scopes for
names A name is a term used for identification by an external observer. They can identify a class or category of things, or a single thing, either uniquely, or within a given context. The entity identified by a name is called its referent. A persona ...
to distinguish them from the same name used elsewhere. In a block-structured programming language, the objects named in outer blocks are visible inside inner blocks, unless they are masked by an
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ai ...
declared with the same name.


History

Ideas of block structure were developed in the 1950s during the development of the first
autocode Autocode is the name of a family of "simplified coding systems", later called programming languages, devised in the 1950s and 1960s for a series of digital computers at the Universities of Manchester, Cambridge and London. Autocode was a generic ...
s, and were formalized in the
Algol 58 ALGOL 58, originally named IAL, is one of the family of ALGOL computer programming languages. It was an early compromise design soon superseded by ALGOL 60. According to John Backus The Zurich ACM-GAMM Conference had two principal motives in pro ...
and
Algol 60 ALGOL 60 (short for ''Algorithmic Language 1960'') is a member of the ALGOL family of computer programming languages. It followed on from ALGOL 58 which had introduced code blocks and the begin and end pairs for delimiting them, representing a k ...
reports. Algol 58 introduced the notion of the "compound statement", which was related solely to
control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imper ...
. The subsequent ''Revised Report'' which described the syntax and semantics of Algol 60 introduced the notion of a block and
block scope In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts o ...
, with a block consisting of " A sequence of declarations followed by a sequence of statements and enclosed between begin and end..." in which " ery declaration appears in a block in this way and is valid only for that block."


Syntax

Blocks use different syntax in different languages. Two broad families are: * the
ALGOL ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
family in which blocks are delimited by the keywords "begin" and "end" or equivalent. In C, blocks are delimited by curly braces - "".
ALGOL 68 ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously de ...
uses parentheses. * Parentheses - "(" and ")", are used in the MS-DOS batch language *
indentation __FORCETOC__ In the written form of many languages, an indentation or indent is an empty space at the beginning of a line to signal the start of a new paragraph. Many computer languages have adopted this technique to designate "paragraphs" or ot ...
, as in
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
*
s-expression In computer programming, an S-expression (or symbolic expression, abbreviated as sexpr or sexp) is an expression in a like-named notation for nested list (tree-structured) data. S-expressions were invented for and popularized by the programming la ...
s with a syntactic keyword such as prog or let (as in the
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
family) * In 1968 (with
ALGOL 68 ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously de ...
), then in
Edsger W. Dijkstra Edsger Wybe Dijkstra ( ; ; 11 May 1930 – 6 August 2002) was a Dutch computer scientist, programmer, software engineer, systems scientist, and science essayist. He received the 1972 Turing Award for fundamental contributions to developing progra ...
's 1974
Guarded Command Language The Guarded Command Language (GCL) is a programming language defined by Edsger Dijkstra for predicate transformer semantics in EWD472. It combines programming concepts in a compact way. It makes it easier to develop a program and its proof hand-in-h ...
the conditional and iterative code block are alternatively terminated with the block reserved word ''reversed'': e.g. if ~ then ~ elif ~ else ~ fi, case ~ in ~ out ~ esac and for ~ while ~ do ~ od


Limitations

Some languages which support blocks with declarations do not fully support all declarations; for instance many C-derived languages do not permit a function definition within a block (
nested function In computer programming, a nested function (or nested procedure or subroutine) is a function which is defined within another function, the ''enclosing function''. Due to simple recursive scope rules, a nested function is itself invisible outside o ...
s). And unlike its ancestor Algol, Pascal does not support the use of blocks with their own declarations inside the begin and end of an existing block, only compound statements enabling sequences of statements to be grouped together in if, while, repeat and other control statements.


Basic semantics

The semantic meaning of a block is twofold. Firstly, it provides the programmer with a way for creating arbitrarily large and complex structures that can be treated as units. Secondly, it enables the programmer to limit the scope of variables and sometimes other objects that have been declared. In early languages such as Fortran IV and
BASIC BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...
, there were no statement blocks or control structures. Conditionals were implemented using conditional
goto GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function ca ...
statements: C LANGUAGE: ANSI STANDARD FORTRAN 66 C INITIALIZE VALUES TO BE CALCULATED PAYSTX = .FALSE. PAYSST = .FALSE. TAX = 0.0 SUPTAX = 0.0 C SKIP TAX DEDUCTION IF EMPLOYEE EARNS LESS THAN TAX THRESHOLD IF (WAGES .LE. TAXTHR) GOTO 100 PAYSTX = .TRUE. TAX = (WAGES - TAXTHR) * BASCRT C SKIP SUPERTAX DEDUCTION IF EMPLOYEE EARNS LESS THAN SUPERTAX THRESHOLD IF (WAGES .LE. SUPTHR) GOTO 100 PAYSST = .TRUE. SUPTAX = (WAGES - SUPTHR) * SUPRAT 100 TAXED = WAGES - TAX - SUPTAX The logical structure of the program is not reflected in the language, and analyzing when a given statement is executed can be difficult. Blocks allow the programmer to treat a group of statements as a unit, and the default values which had to appear in initialization in this style of programming can, with a block structure, be placed closer to the decision: if wages > tax_threshold then begin paystax := true; tax := (wages - tax_threshold) * tax_rate if wages > supertax_threshold then begin pays_supertax := true; supertax := (wages - supertax_threshold) * supertax_rate end else begin pays_supertax := false; supertax := 0 end end else begin paystax := false; pays_supertax := false; tax := 0; supertax := 0 end; taxed := wages - tax - supertax; Use of blocks in the above fragment of
Pascal Pascal, Pascal's or PASCAL may refer to: People and fictional characters * Pascal (given name), including a list of people with the name * Pascal (surname), including a list of people and fictional characters with the name ** Blaise Pascal, Fren ...
clarifies the programmer's intent, and enables combining the resulting blocks into a nested hierarchy of conditional statements. The structure of the code reflects the programmer's thinking more closely, making it easier to understand and modify. The above source code can be made even clearer by taking the inner if statement out of the outer one altogether, placing the two blocks one after the other to be executed consecutively. Semantically there is little difference in this case, and the use of block structure, supported by indenting for readability, makes it easy for the programmer to refactor the code. In primitive languages, variables had broad scope. For instance, an integer variable called IEMPNO might be used in one part of a Fortran subroutine to denote an employee social security number (ssn), but during maintenance work on the same subroutine, a programmer might accidentally use the same variable, IEMPNO, for a different purpose, and this could result in a bug that was difficult to trace. Block structure makes it easier for programmers to control scope to a minute level. ;; Language: R5RS Standard Scheme (let ((empno (ssn-of employee-name))) (while (is-manager empno) (let ((employees (length (underlings-of empno)))) (printf "~a has ~a employees working under him:~%" employee-name employees) (for-each (lambda (empno) ;; Within this lambda expression the variable empno refers to the ssn ;; of an underling. The variable empno in the outer expression, ;; referring to the manager's ssn, is shadowed. (printf "Name: ~a, role: ~a~%" (name-of empno) (role-of empno))) (underlings-of empno))))) In the above
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
fragment, empno is used to identify both the manager and their underlings each by their respective ssn, but because the underling ssn is declared within an inner block it does not interact with the variable of the same name that contains the manager's ssn. In practice, considerations of clarity would probably lead the programmer to choose distinct variable names, but they have the choice and it is more difficult to introduce a bug inadvertently.


Hoisting

In some languages, a variable can be declared at function scope even within enclosed blocks. For example, in JavaScript, variables declared with var have function scope.


See also

*
Basic block In compiler construction, a basic block is a straight-line code sequence with no branches in except to the entry and no branches out except at the exit. This restricted form makes a basic block highly amenable to analysis. Compilers usually decom ...
*
Block scope In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts o ...
*
Closure (computer programming) In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function toge ...
*
Control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an ''imper ...


References

{{DEFAULTSORT:Statement Block Programming constructs