Block (programming): Difference between revisions

Content deleted Content added
No edit summary
Tags: Mobile edit Mobile web edit
Syntax: added Haskell to offside rule
 
(46 intermediate revisions by 38 users not shown)
Line 1:
{{Short description|Lexical structure of source code grouped together}}
{{distinguish|Block programming}}
{{redirect|Code block|the IDE|Code::Blocks|block-based programming|Visual programming language}}
{{refimprove|date=May 2010}}
 
In [[computer programming]], a '''block''' or '''code block''' or '''block of code''' is a lexical structure of [[source code]] which is grouped together. Blocks consist of one or more [[Declaration (computer programming)|declarations]] and [[Statement (computer science)|statements]]. A [[programming language]] that permits the creation of blocks, including blocks [[Nesting (computing)|nested]] within other blocks, is called a '''block-structured programming language'''. Blocks are fundamental to [[structured programming]], where [[control structure]]s are formed from blocks.
 
TheBlocks functionhave oftwo blocksfunctions: into programminggroup isstatements toso enablethat groupsthey of statements tocan be treated as if they were one statement, and to narrow thedefine [[lexicalscope scope(computer science)|scopes]] offor variables,[[name proceduresbinding|names]] andto functionsdistinguish declaredthem in a block so that they do not conflict with variables havingfrom the same name used elsewhere in a program for different purposes. In a block-structured programming language, the names of variables and other objects such as procedures which are declarednamed in outer blocks are visible inside other inner blocks, unless they are [[VariableName shadowingmasking|shadowedmasked]] by an [[Object (computer science)|object]] ofdeclared with the same name.
 
==History==
Ideas of block structure were developed in the 1950s during the development of the first [[autocode]]s, and were formalized in the [[Algol 58]] and [[Algol 60]] reports. Algol 58 introduced the notion of the "compound statement", which was related solely to [[control flow]].<ref name="algol58_report">{{cite journal
|last1= Perlis |first1 = A. J. |authorlink1author-link1=Alan Perlis
|last2= Samelson |first2= K.
| date = 1958
Line 16 ⟶ 21:
| issue = 12
| pages = 8–22
|s2cid = 28755282 | doi-access = free
}}</ref> The subsequent ''Revised Report'' which described the syntax and semantics of Algol 60 introduced the notion of a block and [[block 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."<ref name="algol60_report">{{cite journal
}}</ref> The subsequent ''Revised Report'' which described the syntax and semantics of Algol 60 introduced the notion of a block and [[block 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."<ref name="algol60_report">{{cite journal |last1=Backus |first1=J. W. |author-link1=John Backus |last2=Bauer |first2=F. L. |author-link2=Friedrich L. Bauer |last3=Green |first3=J. |last4=Katz |first4=C. |last5=McCarthy |first5=J. |last6=Perlis |first6=A. J. |last7=Rutishauser |first7=H. |author-link7=Heinz Rutishauser |last8=Samelson |first8=K. |last9=Vauquois |first9=B. |author-link9=Bernard Vauquois |last10=Wegstein |first10=J. H. |last11=van Wijngaarden |first11=A. |last12=Woodger |first12=M. |date=May 1960 |editor1-last=Naur |editor1-first=Peter |title=Report on the Algorithmic Language ALGOL 60 |url=http://www.masswerk.at/algol60/report.htm |journal=Communications of the ACM |___location=New York, NY, USA |publisher=ACM |volume=3 |issue=5 |pages=299–314 |doi=10.1145/367236.367262 |issn=0001-0782 |s2cid=278290 |access-date=2009-10-27 |doi-access=free |editor1-link=Peter Naur}}</ref>
| first1=J. W. |last1=Backus |authorlink1=John Backus
| first2=F. L. |last2=Bauer |authorlink2=Friedrich L. Bauer
| first3=J. |last3=Green
| first4=C. |last4=Katz
| first5=J. |last5=McCarthy
| first6=A. J. |last6=Perlis
| first7=H. |last7=Rutishauser |authorlink7=Heinz Rutishauser
| first8=K. |last8=Samelson
| first9=B. |last9=Vauquois
| first10=J. H.|last10=Wegstein
| first11=A. |last11=van Wijngaarden
| first12=M. |last12=Woodger
| editor1-last=Naur | editor1-first=Peter |editor1-link=Peter Naur
| date=May 1960
| title=Report on the Algorithmic Language ALGOL 60
| publisher= ACM
| ___location = New York, NY, USA
| doi=10.1145/367236.367262
| issn=0001-0782
| volume = 3
| issue = 5
| pages = 299–314
| url = http://www.masswerk.at/algol60/report.htm
| accessdate = 2009-10-27
}}</ref>
 
==Syntax==
Blocks use different syntax in different languages. TwoSeveral broad families are:
 
* the [[ALGOL]] family in which blocks are delimited by the keywords "<code>begin</code>" and "<code>end</code>"
* the [[C (programming language)|C]] family in which blocks are delimited by curly braces - "<code>{</code>" and "<code>}</code>"
 
Some other techniques used are as follows :
 
* parenthesesthe -[[ALGOL]] family in which blocks are delimited by the keywords "<code>(begin</code>" and "<code>)end</code>", asor inequivalent. In [[batchC (programming language)|C]], blocks are delimited by curly braces - "<code>{</code>" and "<code>}</code>". [[ALGOL 68]] uses parentheses.
* Parentheses - "<code>(</code>" and "<code>)</code>", are used in the MS-DOS [[batch language]]
* [[off-side rule|indentation]], as in [[Python (programming language)|Python]]
* [[soff-expressionside rule|indentation]]s with a syntactic keyword such, as <code>lambda</code> or <code>let</code> (as in the [[LispPython (programming language)|LispPython]] family)and [[Haskell]]
* [[s-expression]]s with a syntactic keyword such as <code>prog</code> or <code>let</code> (as in the [[Lisp (programming language)|Lisp]] family)
* In 1968 (with [[ALGOL 68]]), then in [[Edsger W. Dijkstra]]'s 1974 [[Guarded Command Language#Selection: if|Guarded Command Language]] the conditional and iterative code block are alternatively terminated with the block reserved word ''reversed'': e.g. <code><u>'''if'''</u> ~ <u>then</u> ~ <u>elif</u> ~ <u>else</u> ~ <u>'''fi'''</u></code>, <code><u>'''case'''</u> ~ <u>in</u> ~ <u>out</u> ~ <u>'''esac'''</u></code> and <code><u>for</u> ~ <u>while</u> ~ <u>'''do'''</u> ~ <u>'''od'''</u></code>
 
==Limitations==
Some languages which support blocks with variable declarations do not fully support all declarations; for instance many C-derived languages do not permit a function definition within a block ([[nested function]]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 primitiveearly languages such as early [[Fortran IV]] and [[BASIC]], there were a few built-inno statement types, and littleblocks or nocontrol meansstructures ofother extendingthan themsimple informs aof structured mannerloops. ForConditionals instance,were untilimplemented 1978using standard Fortran had no "block if" statement, so to write a standard-complying code to implement simple decisions the programmer had to resort toconditional [[goto]]s statements:
 
<sourcesyntaxhighlight lang="fortranfortranfixed">
C LANGUAGE: ANSI STANDARD FORTRAN 66
C INITIALIZE VALUES TO BE CALCULATED
Line 80 ⟶ 57:
SUPTAX = (WAGES - SUPTHR) * SUPRAT
100 TAXED = WAGES - TAX - SUPTAX
</syntaxhighlight>
</source>
 
EvenThe in this very brief Fortran fragment, written to the Fortran 66 standard, it is not easy to see thelogical structure of the program, because that structure is not reflected in the language., Withoutand carefulanalyzing study it is not easy to see the circumstances in whichwhen 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:
 
<sourcesyntaxhighlight lang="pascal">
{ Language: Jensen and Wirth Pascal }
if wages > tax_threshold then
Line 97 ⟶ 74:
out of the outer conditional altogether and the effects of doing
so are easily predicted. }
if wages > supertax_threshold then begin
begin
pays_supertax := true;
supertax := (wages - supertax_threshold) * supertax_rate
end
else begin
pays_supertax := false;
supertax := 0
end
end
end
else begin
paystax := false; pays_supertax := false;
tax := 0; supertax := 0
end;
taxed := wages - tax - supertax;
</syntaxhighlight>
</source>
 
Use of blocks in the above fragment of [[Pascal (programming language)|Pascal]] enablesclarifies the programmer's to be clearer about what he or she intendsintent, and toenables combinecombining the resulting blocks into a nested hierarchy of [[Conditional (computer programming)|conditional]] statements. The structure of the code reflects the programmer's thinking more closely, making it easier to understand and modify.
 
FromThe lookingabove at the abovesource code the programmer can easilybe see that he or she can make the source codemade 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.
 
<sourcesyntaxhighlight lang="scheme">
;; Language: R5RS Standard Scheme
(let ((empno (ssn-of employee-name)))
Line 127 ⟶ 103:
(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,
Line 135 ⟶ 111:
(role-of empno)))
(underlings-of empno)))))
</syntaxhighlight>
</source>
 
In the above [[Scheme (programming language)|Scheme]] fragment, empno is used to identify both the manager and his or hertheir 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 he or shethey hashave 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 <code>var</code> have function scope.
In a few circumstances, code in a block is evaluated as if the code were actually at the top of the block or outside the block. This is often colloquially known as ''hoisting'', and includes:
* [[Loop-invariant code motion]], a compiler optimization where code in the loop that is invariant is evaluated before the loop;
* [[Variable hoisting]], scope rule in JavaScript, where variables have function scope, and behave as if they were declared (but not defined) at the top of a function.
 
==See also==
Line 153 ⟶ 127:
==References==
{{Reflist}}
{{Programming paradigms navbox}}
 
{{DEFAULTSORT:Statement Block}}
[[Category:Programming constructs]]