Topic 03: Variable Names, Binding, Scope and life
time
Objective
Knowing variables names and binding in C, PHP, Python and Matlab languages
Current Lab Learning Outcomes (LLO)
By completion of the lab the students should be able to
1. Know variables names and binding in C, PHP and Python languages.
Activity Outcomes:
Students should get familiar with:
• How to declare variable names and binding in the three languages.
Lab Description
Variables:
Variables are data objects that are manipulated in a program. Information can be stored in a variable and recalled
later. Variables must be declared before they can be used in a program. A variable is a sextuple (name, address,
value, type, lifetime, scope):
• Name - most variables have an identifier (name) by which the variable may be referred to. The
association between the variable and its name is a name binding.
• Type - in many programming languages, variables have a designated type specifying which values may
be stored in the variable. For example, an int variable in Java can store any integer value in the range -
(2^31) .. (2^31)-1
• Address - in some programming languages, each variable has an address, which is a value denoting
where in memory the variable's storage is located. Most C and C++ variables have addresses.
• Value - at any given point in the execution of the program, a variable will either be uninitialized, or will
contain a value (chosen from the range of values allowed by the variable's type.)
• Scope - part of a program where a variable is accessible its scope
• Lifetime - how long the variable will continue to exist
1|Page
Notes:
• Some variable attributes can be determined without running the program. These attributes are
called static. For example, a variable's name is generally determined without running the program.
• However, some variable attributes are dynamic, meaning that in general they are not known until the
program runs. For example, the value of a variable is generally not known until the program runs, and
even then it may change many times during the program's execution.
Binding:
Each name in a program is used to refer to some "entity" in the program. Possible entities could refer to include:
(variable, constant value, procedure (i.e.: function or method), data type). A name binding is an association
between a particular name used in a program and the entity to which the name refers.
Example: int x=4
xà 4
Type Binding:
A programming language can bind types to variables either statically or dynamically.
1. Static type binding
In a language with static type binding, the type of a variable is always known without running the program. The
C-based languages are statically typed.
int x;
x = 43;
Note that C and C++ have some "holes" in their static type binding rules. For example, C and C++ perform
implicit numeric conversions in some contexts.
int a;
a = 43.5;
The above code is legal in a C or C++ program, even though the double value 43.5 cannot legally be stored in a
variable whose type is "int". What actually happens is that the double value is implicitly converted to the int
value 43 (truncating the value.)
2|Page
2. Dynamic type binding
Many languages use dynamic type binding, where a variable's type changes depending on what value is stored
in it. For example, Python language is dynamically type binding. Example:
>>> x=2
>>>x=3.1
>>>x=’a’
>>>x=”CPCS301”
At first x’s data type was “int” because the value ‘2’ was assigned, then the type change to float when we
assigned ‘3.1’. Whenever a different value is assigned, x data type will change.
C Language
Variables in C:
1. Variables in C are pre-determined typed.
2. The variable name can be 31 characters long.
3. The variable name can be any of a-z, A-Z, 0-9 and the underscore.
4. The variable name should not be a keyword.
5. First character in a variable name must be only an alphabet or underscore.
6. The variable name is case sensitive.
7. A variable name should not contain spaces.
#include <stdio.h>
void main ( )
{
int age=20, Age=25;
printf (“ %d First Age \n”, Age) ;
printf (“ %d Second Age \n”, age) ;
}
The output:
25 First Age
20 Second Age
3|Page
Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
3. static variable
Local Variables
• Definition: A variable that is declared inside the function or block is called a local variable. You must
have to initialize the local variable before it is used.
• Scope: Limited to the block or function in which it is declared.
• Lifetime: Exists only while the function is executing.
• Usage: Must be initialized before use.
• Initialization: Local variables are not automatically initialized to a default value when declared. If you
try to use a local variable without assigning it an initial value, it may contain garbage data
(unpredictable values left in memory).
void function1(){
int x=10;//local variable}
Global Variables
• Definition: A variable that is declared outside the function or block is called a global variable.
Any function can change the value of the global variable. It is available to all the functions.
• Scope: Available to all functions within the program.
• Lifetime: Exists throughout the program execution.
• Usage: Can be modified by any function, which may lead to unintended side effects if not
managed carefully.
• Initialization: Automatically initialized to a default value if not explicitly initialized.
• The default values depend on the variable type:
o Integers (int, long) → 0
o Floating-point (float, double) → 0.0
o Pointers → NULL
• Reason: Global variables are stored in the data segment of memory, which is initialized to
default values by the operating system.
It must be declared at the start of the block.
int value=20;//global variable
void function1(){
int x=10;//local variable}
4|Page
Static Variable
• Definition: A variable that is declared with the static keyword is called static variable. It retains its
value between multiple function calls.
• Scope: Similar to local variables, but their value persists between function calls.
• Lifetime: Exists throughout the program execution but remains accessible only within the block where
it was declared.
• Usage: Useful for retaining values across multiple invocations of a function.
• Initialization: Automatically initialized to a default value if not explicitly initialized.
• The default values depend on the variable type:
o Integers (int, long) → 0
o Floating-point (float, double) → 0.0
o Pointers → NULL
• Reason: Static variables are stored in the data segment of memory, which is initialized to default values
by the operating system.
• Behavior: Retain their value between function calls.
void function1(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y); }
If you call this function many times, the local variable will print the same value for each function call, e.g,
11,11,11 and so on. But the static variable will print the incremented value in each function call, e.g. 11, 12,
13 and so on.
Constants:
A constant is an entity whose value does not change during program execution. Constants are of four different
types
1. Integer Constants
2. Floating point Constants
3. Character Constants
4. String Constants
Constants in C:
There are two ways to define constant in C programming.
1) C const keyword
The const keyword is used to define constant in C programming.
const float PI=3.14;
5|Page
Now, the value of PI variable can't be changed.
#include<stdio.h>
int main(){
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;}
Output:
The value of PI is: 3.140000
If you try to change the value of PI, it will render compile time error.
#include<stdio.h>
int main(){
const float PI=3.14;
PI=4.5;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
Compile Time Error: Cannot modify a const object
2) C #define preprocessor
The #define preprocessor directive is used to define constant. It can use any basic data type.
Syntax: #define token value
Example:
#include <stdio.h>
#define PI 3.14
void main() {
printf("%f",PI);
}
Output:
3.140000
Python Language:
Variables in Python:
• Variables in Python are dynamically typed.
• Variables are not declared, they are just assigned a value.
• Variables can change type by assigning it to an object of a different type.
• The variable name can be any of a-z, A-Z, 0-9 and the underscore
6|Page
• First character in a variable name must be an alphabet or underscore.
• The variable name is case sensitive.
• A variable name should not contain spaces
Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator
is the value stored in the variable. For example:
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print (counter)
print (miles)
print (name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively. This
produces the following result:
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example:
a=b=c=1
Here, an integer object is created with the value 1, and all the three variables are assigned to the same memory
location. You can also assign multiple objects to multiple variables. For example −
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and b respectively, and one string
object with the value "john" is assigned to the variable c.
Constant in Python:
usually we don’t use constant in python but there is a way to create them but it will not be discussed here.
PHP Language
Variables in PHP:
• Variables in PHP are dynamically typed.
• Variables are not declared, they are just assigned a value.
• Variables can change type by assigning it to an object of a different type.
• Variables in PHP starts with a $ sign, followed by the name of the variable
• The variable name must begin with a letter or the underscore character
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
7|Page
• A variable name should not contain spaces
• Variable names are case sensitive
Example
<?php
$name = "CPCS301: Programming Languages";
print( $name );
?>
Note: You can use echo function for printing
echo “$name”;
Output:
CPCS301: Programming Languages
Constants in PHP: To create a constant, use the define() function.
Syntax
define(name, value)
Parameters:
• name: Specifies the name of the constant
• value: Specifies the value of the constant
Example:
Create a constant with a case-sensitive name:
<?php
define("x", "CPCS301");
print x;
?>
Constants are automatically global and can be used across the entire script.
Example
This example uses print a constant outside a function, even if it is defined inside the function:
<?php
function myTest() {
define("x", "CPCS301");
}
myTest();
print x;
?>
Scope rules in C, Python and PHP
Variable scope and lifetime
8|Page
Not all variables are accessible from all parts of our program, and not all variables exist for the same amount of
time. Where a variable is accessible and how long it exists depend on how it is defined. We call the part of a
program, where a variable is accessible, its scope, and the duration for which the variable exists its lifetime.
Scope rules in C
Scope of an identifier is the part of the program where the identifier may directly be accessible. C scope rules
can be covered under following two categories.
1. Global Scope: Can be accessed anywhere in a program.
int a;
void main()
{
a = 2;
}
2. Block Scope: A Block is a set of statements enclosed within left and right braces ({ and } respectively).
Blocks may be nested in C (a block may contain other blocks inside it). A variable declared in a block is
accessible in the block and all inner blocks of that block, but not accessible outside the block.
What if the inner block itself has one variable with the same name? If an inner block declares a variable
with the same name as the variable declared by the outer block, then the visibility of the outer block variable
ends at the point of declaration by inner block.
Code Output
#include<stdio.h> x = 10, y = 20
void main() x = 11, y = 41
{ x = 11, y = 20
{
int x = 10, y = 20;
{
printf("x = %d, y = %d\n", x, y);
{
/* y is declared again, so outer block y is not accessible in
this block*/
int y = 40;
x++;
y++;
printf("x = %d, y = %d\n", x, y);
}
// This statement accesses only outer block's variables
printf("x = %d, y = %d\n", x, y);
}
}
}
9|Page
What about functions and parameters passed to functions?
A function itself is a block. Parameters and other local variables of a function follow the same block scope
rules.
Can variables of block be accessed in another subsequent block?*
No, a variable declared in a block can only be accessed inside the block and all inner blocks of this block. For
example, following program produces compiler error.
Code Output
#include<stdio.h> error: 'x'
void main() undeclared (first
{ use in this
{ function)
int x = 10;
}
{
printf("%d", x); // Error: x is not accessible here
}
}
Exercise 1:
predict the output of following program.
Code Output
#include<stdio.h>
void main()
{
int x = 1, y = 2, z = 3;
printf(" x = %d, y = %d, z = %d \n", x, y, z);
{
int x = 10;
float y = 20;
printf(" x = %d, y = %f, z = %d \n", x, y, z);
{
int z = 100;
printf(" x = %d, y = %f, z = %d \n", x, y, z);
}
}
}
Static Variables in C
Static variables have a property of preserving their value even after they are out of their scope. Hence, static
variables preserve their previous value in their previous scope and are not initialized again in the new scope.
Syntax:
static data_type var_name = var_value;
10 | P a g e
A static variable remains in memory while the program is running. A normal or auto variable is destroyed when
a function call where the variable was declared is over. For example, we can use static int to count number of
times a function is called, but an auto variable can’t be used for this purpose.
Example:
#include<stdio.h>
int fun()
{ static int count = 0;
count++;
return count; }
void main()
{ printf("%d ", fun());
printf("%d ", fun()); }
Output:
12
What will be the output if we remove “static”?
Output:
11
Exercise 2:
Trace the following code and show the outputs.
#include <stdio.h>
void sub1()
{ static int x= 9;
int y= 9;
x++;
y++;
printf("%d %d\n",x,y); }
void main()
{ sub1();
sub1();
sub1();}
Scope in Python
A variable which is defined in the main body of a file is called a global variable. It will be visible throughout
the file, and also inside any file which imports that file.
A variable which is defined inside a function is local to that function. It is accessible from the point at which it
is defined until the end of the function, and exists for as long as the function is executing. The parameter names
in the function definition behave like local variables, but they contain the values that we pass into the function
when we call it. When we use the assignment operator (=) inside a function, its default behavior is to create a
new local variable – unless a variable with the same name is already defined in the local scope.
11 | P a g e
Here is an example of variables in different scopes:
# This is a global variable
a = 0
if a == 0:
b = 1
def my_function(c):
# this is a local variable
d = 3
print(c)
print(d)
my_function(7)
# a and b still exist
print(a)
print(b)
# c and d don't exist anymore -- these statements will give us name errors!
print(c)
print(d)
Scope in PHP
Any variable used inside a function is by default limited to the local function scope. For example:
<?php
$a = 1; /* global scope */
function test()
{
print $a; /* reference to local scope variable */
}
test();
?>
12 | P a g e
This script will not produce any output because the print statement refers to a local version of the $a variable,
and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C
language in that global variables in C are automatically available to functions unless specifically overridden by
a local definition. This can cause some problems in that people may inadvertently change a global variable. In
PHP global variables must be declared global inside a function if they are going to be used in that function.
The global keyword
<?php
$a = 1; /* global scope */
function test()
{ global $a;
print $a; }
test();
?>
Output: 1
Example:
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
print $b;
?>
Output: 3
The above script will output 3. By declaring $a and $b global within the function, all references to either
variable will refer to the global version. There is no limit to the number of global variables that can be
manipulated by a function.
13 | P a g e