Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Block (programming)

From Wikipedia, the free encyclopedia
Demarcated group of source code statements that run in sequence
Not to be confused withBlock programming.
"Code block" redirects here. For the IDE, seeCode::Blocks. For block-based programming, seeVisual programming language.
icon
This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Block" programming – news ·newspapers ·books ·scholar ·JSTOR
(May 2010) (Learn how and when to remove this message)

Incomputer programming, ablock ofsource code is a grouping ofstatements thatexecute in sequential order; top to bottom. The block structure is fundamental tostructured programming, wherecontrol structures are formed with blocks.Syntactically, a block acts much like a single statement in that a control structure generally operates either on a single statement or a block.

The nature of a block varies byprogramming language, but there are typical features. A block usually provides for visibilityscope such that anidentifier defined in a block is not visible in outer, containing blocks, but is visible in inner,nested blocks unless it ismasked by an identifier with the same name. A block usually provides for lifetime scope such thatresources associated with an identifier are partially or fully released whencontrol flow reaches the end of the block in which the identifier was defined.

History

[edit]

The block concept was developed in the 1950s during the development of the firstautocodes, and was formalized in theAlgol 58 andAlgol 60 reports. Algol 58 introduced the notion of the "compound statement", which was related solely tocontrol flow.[1] The subsequentRevised Report which described the syntax and semantics of Algol 60 introduced the notion of a block andblock scope, with a block consisting of " A sequence of declarations followed by a sequence of statements and enclosed between begin and end..." in which "[e]very declaration appears in a block in this way and is valid only for that block."[2]

Syntax

[edit]

A block is demarcated in code as a separate unit, but the syntax varies by language. Notable examples include:

Curly braces
C and many related languages delimit a block with{ and}. In fact, this is the defining quality of acurly brace language.
Indentation
Python andHaskell useindentation to demarcate a block instead of delimiters as most languages do.
Parentheses
Thebatch file syntax uses( and).
begin/end
TheALGOL family generally delimits a block with the keywordsbegin andend;ALGOL 68 uses parentheses.
Control verb reversed
WithALGOL 68, then inEdsger W. Dijkstra's 1974Guarded Command Language the conditional and iterative code block are alternatively terminated with the block reserved wordreversed: e.g.if ~ then ~ elif ~ else ~fi,case ~ in ~ out ~esac andfor ~ while ~do ~od.
S-expression
With a syntactic keyword such asprog orlet as in theLisp family.

Limitations

[edit]

Some languages which support declarations in a block do not support all declarations. For instance, many C-related languages do not permit afunction definition within a block. 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 inif,while,repeat and other control statements.[clarification needed]

Examples

[edit]

In the early days of computing, many languages such asFORTRAN IV andBASIC lacked block syntax except sometimes for rudimentary loop constructs. A conditional was encoded using thegoto statement. In the following FORTRAN 66 code, the logical structure is less than clear due to the lack of blocks.

C     INITIALIZE VALUES TO BE CALCULATEDPAYSTX=.FALSE.PAYSST=.FALSE.TAX=0.0SUPTAX=0.0C     SKIP TAX DEDUCTION IF EMPLOYEE EARNS LESS THAN TAX THRESHOLDIF(WAGES.LE.TAXTHR)GOTO100PAYSTX=.TRUE.TAX=(WAGES-TAXTHR)*BASCRTC     SKIP SUPERTAX DEDUCTION IF EMPLOYEE EARNS LESS THAN SUPERTAX THRESHOLDIF(WAGES.LE.SUPTHR)GOTO100PAYSST=.TRUE.SUPTAX=(WAGES-SUPTHR)*SUPRAT  100TAXED=WAGES-TAX-SUPTAX

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. The following code in Jensen and Wirth Pascal shows that block structure makes it easier to see how the code could be refactored for clarity, and also makes it easier to do, because the structure of the inner conditional can easily be moved out of the outer conditional altogether and the effects of doing so are easily predicted. Use of blocks in the fragment below clarifies the programmer's intent, and enables combining the resulting blocks into a nested hierarchy ofconditional statements. The structure of the code reflects the programmer's thinking more closely, making it easier to understand and modify. The 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.

ifwages>tax_thresholdthenbeginpaystax:=true;tax:=(wages-tax_threshold)*tax_rateifwages>supertax_thresholdthenbeginpays_supertax:=true;supertax:=(wages-supertax_threshold)*supertax_rateendelsebeginpays_supertax:=false;supertax:=0endendelsebeginpaystax:=false;pays_supertax:=false;tax:=0;supertax:=0end;taxed:=wages-tax-supertax;

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.

In the following R5RS Standard Scheme 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. Within the 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.

(let((empno(ssn-ofemployee-name)))(while(is-managerempno)(let((employees(length(underlings-ofempno))))(printf"~a has ~a employees working under him:~%"employee-nameemployees)(for-each(lambda(empno)(printf"Name: ~a, role: ~a~%"(name-ofempno)(role-ofempno)))(underlings-ofempno)))))

Hoisting

[edit]

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

See also

[edit]

References

[edit]
  1. ^Perlis, A. J.; Samelson, K. (1958)."Preliminary report: international algebraic language".Communications of the ACM.1 (12). New York, NY, USA: ACM:8–22.doi:10.1145/377924.594925.S2CID 28755282.
  2. ^Backus, J. W.;Bauer, F. L.; Green, J.; Katz, C.; McCarthy, J.; Perlis, A. J.;Rutishauser, H.; Samelson, K.;Vauquois, B.; Wegstein, J. H.; van Wijngaarden, A.; Woodger, M. (May 1960).Naur, Peter (ed.)."Report on the Algorithmic Language ALGOL 60".Communications of the ACM.3 (5). New York, NY, USA: ACM:299–314.doi:10.1145/367236.367262.ISSN 0001-0782.S2CID 278290. Retrieved2009-10-27.
Imperative
Structured
Object-oriented
(comparison,list)
Declarative
Functional
(comparison)
Dataflow
Logic
Domain-
specific
language

(DSL)
Concurrent,
distributed,
parallel
Metaprogramming
Separation
of concerns
Retrieved from "https://en.wikipedia.org/w/index.php?title=Block_(programming)&oldid=1319449198"
Category:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp