KEMBAR78
Principles of Programming Language - Chapter 5 | PDF | Scope (Computer Science) | Variable (Computer Science)
0% found this document useful (0 votes)
8 views26 pages

Principles of Programming Language - Chapter 5

Deduced from concepts of programming language book by Robert Sebesta

Uploaded by

likhi4951
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views26 pages

Principles of Programming Language - Chapter 5

Deduced from concepts of programming language book by Robert Sebesta

Uploaded by

likhi4951
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Chapter 5

5.1 – Introduction
What’s This Chapter About?
This chapter introduces key ideas related to variables in programming
languages.

It covers:

What names are

What variables are

How variables are linked to things like memory, types, and values

How long variables live in memory (lifetime)

Where variables can be accessed (scope)

Concepts like binding, referencing environments, and named


constants

Why Do Variables Matter in Programming Languages?


Most programming languages are designed based on the von Neumann
architecture.

This architecture includes:

A memory that stores data and instructions

A processor that changes data in memory

Variables in programming languages are just abstractions (simplified


representations) of memory cells.

How Closely Do Variables Resemble Memory?


Sometimes, variables directly map to how memory works.

Example: An int variable that fits in 4 bytes.

Sometimes, they are much more complex.

Chapter 5 1
Example: A 3D array needs extra logic (software) to manage how it’s
stored in memory.

What Are the Main Properties of a Variable?


A variable has attributes (properties) like:

Its name

Its type (e.g., int , float )

Its memory address

Its value

Its lifetime

Its scope

📝 Note: Type is one of the most important attributes.


Chapter 6 explains types in detail.

What About Functional Programming Languages?


In functional languages:

You can give names to expressions, which look like assigning values to
variables.

But once set, they can’t be changed — like named constants in


imperative (C-like) languages.

True functional languages don’t have changeable variables, but many


modern ones do include them.

Language Families and Naming in This Book


When the book says “Fortran,” it means all versions of Fortran.

Example: “Fortran 95+” = Fortran 95 and later versions.

Same goes for:

C = C, C89, C99

Ada = All versions of Ada

Chapter 5 2
C-based languages refers to:

C, C++, Java, C#, Objective-C

(Even though JavaScript and PHP look similar, they’re not treated as C-
based here.)

5.2 Names
What Are Names in Programming?
A name is a string of characters used to refer to something in a program.

Names are commonly used to label:

Variables

Constants

Functions

Classes

Methods

Modules

Operations (like + , == , etc.)

Why Are Names Important?


Without names, it would be impossible to write programs that:

Use variables

Organize functions

Call subroutines

Pass data around

They allow us to write meaningful and readable code like:

total = sum + bonus;

Instead of referring to raw memory addresses or hardcoded values.

Chapter 5 3
Lexemes and Names

✅ What Is a Lexeme?
A lexeme is the actual sequence of characters that make up a word or
symbol in your program.

Examples:

count

print

3.14

✅ What Is a Name?
A name is a lexeme that is associated with some entity in the language.

Example:

int x = 5;

x is the name of the variable.

The string x is the lexeme used to refer to it.

How Are Names Formed?

✅ Rules for Naming


Programming languages usually have rules for what counts as a valid
name.

For example, in most C-based languages:

A name must start with a letter or underscore

It can contain letters, numbers, and underscores

It cannot start with a digit

In Fortran:

Chapter 5 4
Early versions limited names to 6 characters

This was because old machines could only read that much

In Python:

Names can include Unicode letters, like those from non-English


languages

So you could (technically) name a variable π = 3.14

Case Sensitivity in Names

✅ What Does “Case Sensitive” Mean?


If a language is case sensitive, it treats count , Count , and COUNT as different
names.

If it’s not case sensitive, then those three are considered the same.

✅ Examples
Language Case Sensitivity

C, C++, Java Yes

Ada, Fortran No

Python Yes

Special Characters in Names


Some languages allow special characters in names.

Perl and Ruby: Allow $ , @ , % at the start of names to show variable


types.

Example: $total , @list , %hash

ML, F#, and Prolog: Use symbols like ' or ` in names.

Example: x' or `add

These are usually allowed only under specific rules in each language.

Chapter 5 5
5.3 Variables
What Is a Variable in Programming?
A variable is a named container in memory that holds a value.

It acts like a label for a memory cell, so you can store and change
information in your program.

Variables Represent Memory Cells


In most programming languages (especially imperative ones), each variable
is directly tied to one or more memory cells.

The name (like x ) helps us access or modify what's stored in those cells.

What Are the Key Properties (Attributes) of a


Variable?
Every variable has the following attributes:

✅ 1. Name
The identifier used to refer to the variable.

Example: x , totalScore , counter

✅ 2. Address
The memory location where the variable's value is stored.

In simple cases, a variable refers to one address.

In complex structures (like arrays), a variable name may refer to multiple


addresses.

Example:

int x = 10;

x is the name

Chapter 5 6
Its memory address could be something like 0x7ffe45a8

✅ 3. Value
The data stored in the memory cell.

You can read or change this value using the variable name.

Example:

x = 5;

5 is the value stored in x .

✅ 4. Type
The kind of data the variable holds.

Examples: int , float , char , bool , string , etc.

The type determines:

The range of values the variable can hold

What operations can be done on it

How much memory it uses

✅ 5. Lifetime
The time period during program execution when the variable exists in
memory.

If a variable is out of scope or deleted, its memory can be reused.

✅ 6. Scope
The region of the program where the variable can be accessed.

Variables can be:

Local (used only inside a function or block)

Global (available throughout the program)

Chapter 5 7
✅ 7. Binding
Binding is the connection between a variable and its properties (like its
type, memory address, or value).

Some bindings are done early (before the program runs), and some during
execution.

How Variables Work in Functional Languages


In pure functional languages, variables don’t change values after being
set.

Instead of changing memory, new values are computed and returned.

So, in those languages:

Variables are more like named expressions or constants

5.4 The Concept of Binding


What Is Binding in Programming?
Binding means creating an association or connection between two things
in a program.

In the context of programming languages, binding usually connects:

A name (like x )

To a property (like a memory address, type, or value)

Examples of What Can Be Bound


A name can be bound to:

1. A type

Example: x is an int

2. A memory location (address)

Example: x refers to address 0x7ffe45a8

3. A value

Chapter 5 8
Example: x = 10

4. A function or method

Example: square is bound to a function that calculates squares

5. A block of code

Example: A label in goto statements (used in some languages)

What Is a Binding Time?

Definition
Binding time = The moment when a binding takes place.

✅ Different Binding Times


1. Language Design Time

Decides rules like data types, control structures, etc.

2. Language Implementation Time

Chooses things like how data types are represented in memory.

3. Compile Time

Binds things like variable names to types (in statically typed languages).

4. Link Time

Connects separately compiled pieces of code (like libraries).

5. Load Time

Binds program instructions and data to actual memory locations when


loaded.

6. Run Time

Happens while the program is executing (e.g., dynamic type binding in


Python).

Early vs. Late Binding

Chapter 5 9
Type When It Happens Example

Early Binding Before program runs C variable types fixed at compile time

Late Binding During execution Python can bind types at run time

Why Binding Time Matters


Early binding usually makes a program run faster and catch more errors
early.

Late binding gives more flexibility, but can be slower and more error-
prone.

Static vs. Dynamic Binding

✅ Static Binding
Happens before the program runs (at compile time or earlier)

Examples:

Variable types in C

Method calls in C++ (if not marked virtual)

✅ Dynamic Binding
Happens while the program is running

Examples:

Method calls using virtual in C++

Dynamic typing in Python and JavaScript

5.5 Type Binding


What Is Type Binding?
Type binding is the process of associating a data type with a variable.

Once a type is bound to a variable, it tells the compiler or interpreter:

Chapter 5 10
What kind of values the variable can hold

What operations can be performed on it

When Can Type Binding Happen?


There are two main types:

✅ 1. Static Type Binding


The type is known before the program runs — usually at compile time.

This happens in statically typed languages like:

C++

Java

Ada

How It Works:

int x = 10;

The variable x is statically bound to the int type.

You cannot change the type of x later in the program.

✅ 2. Dynamic Type Binding


The type is determined during runtime, based on the value assigned.

This happens in dynamically typed languages like:

Python

Ruby

JavaScript

Scheme

How It Works:

Chapter 5 11
x = 10 # x is an int
x = "hello" # now x is a string

The type of x is bound at runtime, and it can change later.

Why Is Type Binding Important?


It helps the language:

Know how much memory to use for variables

Know what operations are allowed

Prevent type errors

Trade-offs Between Static and Dynamic Binding


Binding Type Advantages Disadvantages

Faster execution, early error


Static Less flexible (type can’t change)
detection

More flexible, easy to write Slower performance, errors may


Dynamic
short programs show up at runtime

Intermediate Cases: Type Inference


Some modern languages like Haskell, Rust, and newer versions of C# and
Java support type inference.

This means:

The compiler figures out the type automatically

But the type is still bound statically

Example in C#

var x = 5; // compiler sees that x is an int

The type is not written explicitly, but once bound, it cannot change.

Chapter 5 12
5.6 Storage Bindings and Memory
Management
What Is Storage Binding?
Storage binding is the process of assigning memory to a variable.

This is different from type binding — here, we’re talking about where in
memory the variable actually lives while the program is running.

When Can Storage Be Bound?


There are several stages where a variable can be assigned memory:

✅ 1. Static Storage Binding


The variable is bound to a specific memory location at compile time.

It stays in that same memory location for the entire time the program runs.

Used For:
Global variables

Static variables in languages like C/C++

Advantages:
Very efficient — memory is known early and access is fast.

Disadvantages:
Not flexible — once bound, the memory cannot be reused or resized.

✅ 2. Stack-Dynamic Storage Binding


The variable gets memory when the block or function is called, and is
removed when the block ends.

These variables live in the runtime stack.

Used For:

Chapter 5 13
Local variables in most functions

Parameters passed to functions

Example:

void myFunction() {
int x = 5; // memory for x is allocated when function is called
}

x exists only during the function’s execution.

Advantages:
Supports recursion

Memory is reused after the function ends

Disadvantages:
Slower than static storage

Slight overhead in managing the stack

✅ 3. Explicit Heap-Dynamic Storage Binding


Memory is allocated manually by the programmer from the heap during
runtime.

It stays allocated until the programmer frees it.

Used For:
Objects and dynamic data structures like linked lists, trees, etc.

Examples:
In C:

int* p = (int*) malloc(sizeof(int));

In C++:

Chapter 5 14
int* p = new int;

In Java:

Integer obj = new Integer(5);

Advantages:
Very flexible — great for structures whose size is not known at compile
time.

Disadvantages:
Risk of memory leaks (if memory is not freed)

Slower performance

Harder to manage manually

✅ 4. Implicit Heap-Dynamic Storage Binding


Memory is allocated and deallocated automatically, usually when a value is
assigned.

You don’t have to manually manage the memory.

Used In:
Dynamically typed languages like Python, JavaScript, Lisp

Example (Python):

x = 10 # memory allocated for integer


x = "hi" # old memory is discarded, new string allocated

Advantages:
Very easy for programmers — no need to worry about memory
management.

Chapter 5 15
Disadvantages:
Slowest method

Can use more memory than needed

Harder to control performance

Memory Management Concepts

✅ Manual Memory Management


The programmer is responsible for both:

Allocating memory (e.g., malloc() )

Deallocating memory (e.g., free() )

Languages: C, C++

✅ Automatic Memory Management (Garbage Collection)


The system automatically frees memory that is no longer being used.

Languages: Java, Python, JavaScript

How Garbage Collection Works


The system tracks which objects or variables are still being referenced.

If something is no longer reachable, the memory is reclaimed.

5.7 Lifetime and Scope

What Is Lifetime?

✅ Definition
Lifetime is the time period during which a variable exists in memory —
from when it’s allocated to when it’s deallocated.

It's about how long the variable lives, not where it can be accessed.

Chapter 5 16
✅ Lifetime Depends on Storage Type
Storage Type When It’s Allocated When It’s Deallocated

Static At program start At program end

Stack-Dynamic When block/function starts When block/function ends

Explicit Heap When programmer requests it When programmer frees it

Implicit Heap Automatically during runtime Automatically when unused (GC)

What Is Scope?

✅ Definition
Scope is the part of the program where a variable can be used or
accessed by name.

A variable can only be used within its scope — otherwise it’s considered
undefined.

✅ Types of Scope
1. Static Scope (Lexical Scope)
The variable’s scope is determined by where it is written in the source
code.

You can tell what a name refers to just by looking at the code, without
running it.

Most modern languages (like C, Java, Python, etc.) use static scope.

Example:

int x = 5; // global x

void func() {
int x = 10; // local x
printf("%d", x); // prints 10
}

Chapter 5 17
The x inside func is in a different scope than the global x .

2. Dynamic Scope
The variable’s scope depends on the call stack at runtime, not on where it
is written in the code.

It checks for variable definitions in the calling functions, not in the text
above it.

Rare in modern languages, but used in some versions of Lisp, SNOBOL,


and early BASIC.

Example:

main() {
int x = 5;
func();
}

func() {
print(x); // dynamically finds x in main’s environment
}

In dynamic scope, func would find x from main , because main called it.

Scope Rules: Local vs. Global

✅ Local Scope
A variable defined inside a function or block is local to that block.

It can’t be accessed from outside that function or block.

✅ Global Scope
A variable defined outside all functions is global.

It can be accessed from anywhere in the program (unless shadowed by a


local variable with the same name).

Chapter 5 18
Nested Scopes and Visibility

✅ Nested Scopes
One scope inside another is a nested scope.

Inner scopes can see variables from outer scopes (unless overridden), but
outer scopes cannot see into inner ones.

Example (C-like languages):

int x = 1;

void outer() {
int y = 2;

void inner() {
int z = 3;
// x and y visible here
}

// z NOT visible here


}

✅ Variable Shadowing
If a variable with the same name is declared in an inner scope, it hides the
one in the outer scope.

This is called shadowing.

Block Structure
Most languages are block-structured, meaning each block (like a function
or loop) introduces a new scope.

Examples: C, Java, Python, Ada

Here is the paraphrased version of Section 5.8 – Scope Rules, rewritten clearly
for beginners and formatted cleanly for Google Docs.

Chapter 5 19
It preserves all original content — nothing skipped, only simplified for easier
understanding.

5.8 Scope Rules

What Are Scope Rules?


Scope rules define how a language decides which declaration of a
variable name should be used in a particular part of the code.

If a name is used in more than one place (like multiple variables named x ),
the scope rules decide which x the program refers to.

✅ The Scope Rule’s Job:


Match uses of variables (references) to their declarations.

Static Scope (also called Lexical Scope)

✅ How It Works
In static scope, the structure of the program’s code decides which variable
a name refers to — not the order of execution.

Most modern languages (like C, Java, Python, Ada) use static scope.

✅ Rules for Matching Names


When a variable name is used:

1. Look in the current block for a declaration.

2. If not found, look in the nearest enclosing block.

3. Keep going upward until the declaration is found.

4. If none is found, it's an undefined variable (compiler error).

✅ Example:

Chapter 5 20
int x = 1;

void func() {
int y = 2;

void inner() {
int x = 3;
printf("%d", x); // prints 3, local x shadows global x
}
}

The x=3 in inner() shadows the outer x=1 .

Block Structure and Scope

✅ What Is Block Structure?


A language is block-structured if:

Every block (like {} in C, or begin...end in Pascal) creates a new scope.

This helps control the visibility of variables.

✅ Example (Pascal-style):
program Example;
var x: integer;

procedure A;
var y: integer;

procedure B;
var z: integer;
begin
x := 1; // accesses global x
y := 2; // accesses y from A
z := 3; // local z
end;

Chapter 5 21
begin
B;
end;

begin
A;
end.

In procedure B:

x refers to the outermost x

y comes from procedure A

z is declared inside B

Nesting Levels

✅ What Is a Nesting Level?


Every block in a program has a nesting level, starting from 0.

Block Nesting Level

Outermost block (main) 0

Procedure/function inside main 1

A block inside that 2

This helps the compiler track scope relationships.

Referencing Environments

✅ What Is a Referencing Environment?


The referencing environment of a statement is the set of all variables that
are visible and accessible at that point in the code.

In static scope, the referencing environment is determined just by code


structure.

Chapter 5 22
5.9 Named Constants

What Is a Named Constant?


A named constant is similar to a variable — it has:

A name

A type

A value

But unlike a variable, its value does not change after it is assigned.

✅ Example:
const int MAX_SIZE = 100;

MAX_SIZE is a named constant

It will always hold the value 100

Any attempt to change it later will cause a compiler error

Why Use Named Constants?

✅ Benefits:
1. Improves Readability

Instead of seeing a random number like 100 , you see MAX_SIZE , which
tells you what the number means.

2. Easier Maintenance

If the value changes (e.g., 100 → 200), you only need to change it in
one place, instead of updating it everywhere in the code.

3. Helps Prevent Bugs

Since the value can't be changed accidentally, it makes the code safer
and more predictable.

Chapter 5 23
How Are Named Constants Defined in Different
Languages?

Language How Named Constants Are Declared

C/C++ const int x = 10; or #define X 10

Java final int X = 10;

Python No true constants — by convention, use ALL CAPS: PI = 3.14

Ada X : constant Integer := 10;

Fortran parameter (X = 10)

🔎 In Python and some other languages, constants are not


enforced — it's up to the programmer to follow the rule.

Are Named Constants Bound Early or Late?


Named constants are always bound early, usually at compile time.

This means:

The type and value are fixed before the program runs.

They cannot be changed during execution.

Named Constants in Functional Languages


Functional languages like Haskell or ML don't allow mutable variables by
default.

So, everything behaves like a named constant — once a value is given, it


can't be changed.

5.9 Named Constants

What Is a Named Constant?


A named constant is similar to a variable — it has:

Chapter 5 24
A name

A type

A value

But unlike a variable, its value does not change after it is assigned.

✅ Example:
const int MAX_SIZE = 100;

MAX_SIZE is a named constant

It will always hold the value 100

Any attempt to change it later will cause a compiler error

Why Use Named Constants?

✅ Benefits:
1. Improves Readability

Instead of seeing a random number like 100 , you see MAX_SIZE , which
tells you what the number means.

2. Easier Maintenance

If the value changes (e.g., 100 → 200), you only need to change it in
one place, instead of updating it everywhere in the code.

3. Helps Prevent Bugs

Since the value can't be changed accidentally, it makes the code safer
and more predictable.

How Are Named Constants Defined in Different


Languages?

Language How Named Constants Are Declared

C/C++ const int x = 10; or #define X 10

Chapter 5 25
Language How Named Constants Are Declared

Java final int X = 10;

Python No true constants — by convention, use ALL CAPS: PI = 3.14

Ada X : constant Integer := 10;

Fortran parameter (X = 10)

🔎 In Python and some other languages, constants are not


enforced — it's up to the programmer to follow the rule.

Are Named Constants Bound Early or Late?


Named constants are always bound early, usually at compile time.

This means:

The type and value are fixed before the program runs.

They cannot be changed during execution.

Named Constants in Functional Languages


Functional languages like Haskell or ML don't allow mutable variables by
default.

So, everything behaves like a named constant — once a value is given, it


can't be changed.

Chapter 5 26

You might also like