You are on page 1of 37

Chapter 5

Variables:
Names, Bindings,
Type Checking and Scope

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 1


Introductio
n
This lecture introduces the fundamental
semantic issues of variables
– It covers the nature of names and special words
in programming languages, attributes of
variables, concepts of binding and binding times.
– It investigates type checking, strong typing and
type compatibility rules.
– At the end it discusses named constraints and
variable initialization techniques.

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 2


On
Names
• Humans are the only species to have the concept of a name.
• It’s given philosophers, writers and computer scientists lots
to do for many years.
– The logician Frege’s famous morning star and evening
star example.
– "What's in a name? That which we call a rose by any
other word would smell as sweet." -- Romeo and Juliet,
W. Shakespeare
– The semantic web proposes using URLs as names for
everything.
• In programming languages, names are character strings
used to refer to program entities – e.g., labels, procedures,
parameters, storage locations, etc.

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 3


Names
There are some basic design issues involving names:

– Maximum length?
– What characters are allowed?
– Are names case sensitive?
– Are special words reserved words or keywords?
– Do names determine or suggest attributes

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 4


Names: implied attributes
• We often use conventions that associate
attributes with name patterns.

• Some of these are just style conventions


while others are part of the language spec
and are used by compilers

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 11


Examples of implied attributes
• LISP: global variables begin and end with an asterisk, e.g.,
(if (> t *time-out-in-seconds*) (blue-screen))
• JAVA: class names begin with an upper case character, field
and method names with a lower case character
for(Student s : theClass) s.setGrade(“A”);
• PERL: scalar variable names begin with a $, arrays with @,
and hashtables with %, subroutines begin with a &.
$d1 = “Monday”; $d2=“Wednesday”; $d3= “Friday”;
@days = ($d1, $d2, $d3);
• FORTRAN: default variable type is float unless it begins
with one of {I,J,K,L,M,N} in which case it’s integer
DO 100 I = 1, N
100 ISUM = ISUM + I
CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 12
Variable
s of a memory cell
• A variable is an abstraction

• Can represent complex data structures with lots of


structure (e.g., records, arrays, objects, etc.)

current_student

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 13


Attributes of Variables
Variables can be characterized as a 6-
tuple of attributes:
– Name: identifier used to refer to the variable
– Address: memory location(s) holding the
variables value
– Value: particular value at a moment
– Type: range of possible values
– Lifetime: when the variable can be accessed
– Scope: where in the program it can be
accessed

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 14


Variables
Type
• Typing is a rich subject in Computer Science
• Most languages associate a variable with a single type
• The type determines the range of values and the
operations allowed for a variable
• In the case of floating point, type usually also
determines the precision (e.g., float vs. double)
• In some languages (e.g., Lisp, Python, Prolog) a
variable can take on values of any type.
• OO languages (e.g. Java) have a few primitive types
(int, float, char) and everything else is a pointer to an
object, but the objects form a kind of user-defined type
system
CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 18
Functions have types too

• Procedures or mehtods that return a value


have a type, also: the type of the value
returned
• One of the most common way to describe a
function is by its type signature
• A type signature describes the types of each
input and the type of the output
power: float × integer float

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 19


Contrasts in Type Systems

• Type systems are often described by their


design decisions along several dimensions
– Static vs. dynamic types
– Strong vs. Weak typing
– Explicit vs. implicit type conversion
– Explicit vs. implicit type declarations
• Although the dimensions appear to be binary
choices, there are intermediate choices in
many cases

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 20


Variable
Value
• The value is the contents of the memory
location with which the variable is associated.
• Think of an abstract memory location, rather
than a physical one.
– Abstract memory cell - the physical cell or
collection of cells associated with a variable
• A variable’s type will determine how the bits
in the cell are interpreted to produce a value.
• We sometimes talk about lvalues and rvalues.

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 21


lvalue and
rvalue
Are the two occurrences of “a” in this expression
the same?
a := a + 1;
In a sense,
• The one on the left of the assignment refers to the
location of the variable whose name is a;
• The one on the right of the assignment refers to the
value of the variable whose name is a;
We sometimes speak of a variable’s lvalue and
rvalue
• The lvalue of a variable is its address
• The rvalue of a variable is its value

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 22


Bindin
g
• Def: A binding is an association, such as
between an attribute and an entity, or between an
operation and a symbol
• It’s like assignment, but more general
• We often talk of binding
– a variable to a value, as in
classSize is bound to the number of students
– A symbol to an operator
+ is bound to the inner product operation
• Def: Binding time is the time at which a binding
takes place.

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 23


Possible binding times
• Language design time, e.g., bind operator symbols
to operations
• Language implementation time, e.g., bind floating
point type to a representation
• Compile time, e.g., bind a variable to a type in C or
Java
• Link time
• Load time, e.g., bind a FORTRAN 77 variable to
memory cell (or a C static variable)
• Runtime, e.g., bind a nonstatic local variable to a
memory cell

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 24


Type
• Def: A bindingBindings
is static if it occurs before
run time and remains unchanged throughout
program execution.
• Def: A binding is dynamic if it occurs during
execution or can change during
execution of the program.
• Type binding issues include:
• How is a type specified?
• When does the binding take place?
• If static, type may be specified by either explicit
or an implicit declarations
CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 25
Declarations
• Many languages require or allow the types of
variables and functions to be declared
• Def: An explicit declaration is a program statement
used for declaring the types of variables
• Def: An implicit declaration is a default
mechanism for specifying types of variables (the
first appearance of the variable in the program)

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 26


Implicit Variable Declarations
• Some examples of implicit type declarations
– In C undeclared variables are assumed to be of type int
– In Perl, variables of type scalar, array and hash begin
with a $, @ or %, respectively.
– Fortran variables beginning with I-N are assumed to be
of type integer.
– ML (and other languages) use sophisticated type
inference mechanisms
• Advantages and disadvantages
– Advantages: writability, convenience
– Disadvantages: reliability – requiring explicit type
declarations catches bugs revealed by type mis-matches

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 27


Dynamic Type Binding
• With dynamic binding, a variable’s type can
change as the program runs and might be re-
bound on every assignment.
• Used in scripting languages (Javascript, PHP,
Python) and some older languages (Lisp, Basic,
Prolog, APL)
• In this APL example LIST is first a vector of
integers and then of floats:
LIST <- 2 4 6 8
LIST <- 17.3 23.5
• Here’s a javascript example
list = [2, 4.33, 6, 8];
list = 17.3;
CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 28
Dynamic Type Binding
• The advantages of dynamic typing include
– Flexibility for the programmer
– Obviates the need for “polymorphic” types
– Development of generic functions (e.g. sort)
• But there are disadvantages as well
– Types have to be constantly checked at run time
– A compiler can’t detect errors via type mis-
matches
• Mostly used by scripting languages today

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 29


Static Type Binding
• In a static type system, types are fixed before the
program is run (aka, compile time)
• Compatibility checking can be done by a compiler
and errors flagged
• Some claim that most program errors are type errors
• Another advantage is that the resulting code need
not check for type mismatches at run time, which
speeds up execution
• It typically requires adding type declarations (a pain)
but these can also be seen as a kind of
documentation (a benefit)

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 30


Type Inferencing
• Type inferencing is used in some programming
languages, including ML, Miranda, and Haskell
• Types are determined from the context of the
reference, rather than just by assignment statement
• The compiler can trace how values flow through
variables and function arguments
• The result is that the types of most variables can be
deduced!
Any remaining ambiguity is treated as an error the
programmer must fix by adding explicit declarations
• Many feel it combines the advantages of dynamic
typing and static typing
CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 31
Type Inferencing in ML
fun circumf(r) = 3.14159*r*r; // infer r is real
fun time10(x) = 10*x; // infer r is integer
fun square(x) = x*x; // can’t deduce types
// default type is int
We can explicitly type in several ways and enable the
compiler to deduce that the function returns a real and
takes a real argument
fun square(x):real = x*x;
fun square(x:real) = x*x;
fun square(x) = x:real*x;
fun square(x) = x*x:real;

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 32


Duck Typing
• A kind of dynamic typing typified by Python ad Ruby
• An object's current set of methods and properties
determines the valid semantics, rather than its
inheritance from a particular class
• If it walks like a duck and quacks like a duck, I would
call it a duck.

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 33


Duck Typing example
def calculate(a, b, c): return (a+b)*c

a = calculate(1, 2, 3)
b = calculate([1, 2, 3], [4, 5, 6], 2)
c = calculate('apples ’,'and oranges,', 3)

print ‘a is’, a
print ‘b is’, b
print ‘c is’, c

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 34


Type
Checking
Generalize the concept of operands and operators to
include subprograms and assignments
• Type checking is the activity of ensuring that the operands of an
operator are of compatible types
• A compatible type is one that is either legal for the operator, or
is allowed under language rules to be implicitly converted, by
compiler-generated code, to a legal type.
• This automatic conversion is called a coercion.
• A type error is the application of an operator to an operand of
an inappropriate type
• Note:
• If all type bindings are static, nearly all checking can be static
• If type bindings are dynamic, type checking must be dynamic

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 40


Strong vs. Weak Typing

• We often categorize a programming


languages into two classes:
– Strongly typed
– Weakly typed
• based on their system of assigning types to
variables and functions
• The notions of strong and weak typing do not
have consensus definitions, however

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 41


Strong Typing
Features
A programming language is strongly typed if
• type errors are always detected
• There is strict enforcement of type rules with no
exceptions.
• All types are known at compile time, i.e. are
statically bound.
• With variables that can store values of more than
one type, incorrect type usage can be detected at
run-time.
• Strong typing catches more errors at compile time
than weak typing, resulting in fewer run-time
exceptions.
CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 42
Which languages have strong
• Fortran 77 isn’t because typing?
it doesn’t check parameters and
because of variable equivalence statements.
• The languages Ada, Java, and Haskell are strongly typed.
• Pascal is (almost) strongly typed, but variant records screw it
up
• C and C++ are sometimes described as strongly typed, but are
perhaps better described as weakly typed because parameter
type checking can be avoided and unions are not type checked
• Coercion rules strongly affect strong typing—they can weaken
it considerably (C++ versus Ada)
• See
http://en.wikipedia.org/wiki/Comparison_of_programming_lan
guages#Type_systems

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 43


Weak typing and coersion
• Doing a lot of implicit (automatic) coersion
weakens the type system
• Most languages do it to some degree
X=1
Y = 2.0
X+Y
• But overuse can cause problems
X=1
Y = “2”
X+Y

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 44


Weak typing and coercion
• Doing a lot of implicit (automatic) coercion
weakens the type system
• Most languages do it to some degree
X=1
Many languages
Y = 2.0 will produce the
X+Y float 3.0 for X+Y
• But overuse can cause problems
X=1
X+Y is 3 in Visual
Y = “2” Basic and “12” in
X+Y javascript

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 45


What about Scheme and Python?

• People argue about whether that are strongly or


weakly typed
• Partly it’s because the terms do not have a clear
consensus definition and partly out of confusion
and partly a result of conflating the issue with static
vs. dynamic typing
• Polymorphism and operator overloading obscure
the judgment
• I’m with the camp that describes both as strongly
typed

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 46


Type
Compatibility
•Type compatibility by name means two variables have
compatible types if they are in either the same declaration
or in declarations that use the same type name
Easy to implement but highly restrictive:
• Subranges of integer types aren’t compatible with
integer types
• Formal parameters must be the same type as their
corresponding actual parameters (Pascal)
•Type compatibility by structure means that two variables
have compatible types if their types have identical
structures
More flexible, but harder to implement
CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 47
Subtypes and
ranges
• Some languages such as Ada make it easy to define subtypes,
as in

subtype DAY_NUMBER_T is integer range 1..31;


subtype NATURAL is INTEGER range 0..INTEGER'LAST;
subtype POSITIVE is INTEGER range 1..INTEGER'LAST;

• Pascal made good use of integer ranges

type a = 1..100;
b = -20..20;
c = 0..100000;

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 48


Type Compatibility
Consider the problem of two structured types
Suppose they are circularly defined
• Are two record types compatible if they are structurally
the same but use different field names?
• Are two array types compatible if they are the same except
that the subscripts are different? (e.g. [1..10] and [-5..4])
• Are two enumeration types compatible if their
components are spelled differently?

With structural type compatibility, you cannot


differentiate between types of the same structure
(e.g. different units of speed, both float)

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 49


Type Compatibility Language examples

Pascal: usually structure, but in some cases


name is used (formal parameters)

C: structure, except for records

Ada: restricted form of name


– Derived types allow types with the same
structure to be different
– Anonymous types are all unique, even in:
A, B : array (1..10) of INTEGER:

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 50


Type Safety
• A programming language is type safe if the
only operations that are performed on data in
the language are those sanctioned by the type
of the data
• i.e., no type errors!
• The checking can be done at compile time or
run time
• C is not type safe
• Standard ML has been proven to be type safe
• Haskell is thought to be type safe if you don’t
use some features (type punning)

CMSC331. Some material © 1998 by Addison Wesley Longman, Inc. 51

You might also like