PL 10 CH 5
PL 10 CH 5
Names, Bindings,
and Scopes
Chapter 5 Topics
• Introduction
• Names
• Variables
• The Concept of Binding
• Scope
• Scope and Lifetime
• Named Constants
• Length
– If too short, they cannot be connotative
– Language examples:
• FORTRAN 95: maximum of 31characters
• C99: no limit but only the first 63 are significant;
also, external names are limited to a maximum of
31
• C#, Ada, and Java: no limit, and all are significant
• C++: no limit, but implementers often impose one
• Special characters
– PHP: all variable names must begin with dollar
signs
– Perl: all variable names begin with special
characters
– Ruby: variable names that begin with @ are
instance variables; those that begin with @@
are class variables. Global variables start with
$.
• Case sensitivity
– Disadvantage: readability (names that look
alike are different)
• Names in the C-based languages are case
sensitive
• Ada, Fortran, SQL, and Pascal is not case
sensitive.
• Worse in C++, Java, and C# because predefined
names are mixed case (e.g.
IndexOutOfBoundsException)
• Special words
– An aid to readability; used to delimit or
separate statement clauses
• A keyword is a word that is special only in certain
contexts, e.g., in Fortran
– Real VarName (Real is a data type followed with a name,
therefore Real is a keyword)
– Real = 3.4 (Real is a variable)
• In ML:
let
val name1 = expression1
…
val namen = expressionn
in
expression
end;
• In F#:
– First part: let left_side = expression
– (left_side is either a name or a tuple pattern)
– All that follows is the second part
Copyright © 2012 Addison-Wesley. All rights reserved. 1-26
Declaration Order (continued)
• PHP
– Programs are embedded in HTML markup
documents, in any number of fragments, some
statements and some function definitions
– The scope of a variable (implicitly) declared in
a function is local to the function
– The scope of a variable implicitly declared
outside functions is from the declaration to the
end of the program, but skips over any
intervening functions
• Global variables can be accessed in a function
through the $GLOBALS array or by declaring it global
Copyright © 2012 Addison-Wesley. All rights reserved. 1-29
Evaluation of Static Scoping
– Static scoping
• Reference to x in sub2 is to big's x
– Dynamic scoping
• Reference to x in sub2 is to sub1's x
int g()
{
int x = 20;
return f();
}
int main()
{
printf("%d", g());
printf("\n");
return 0;
}