VARIABLE
S
BICT1201
VARIABLE DEFINITION
WHAT IS A VARIABLE?
VARIABLES
A variable is a named storage location in the computer's
memory that holds a value.
This value can be modified and reused during the execution of a program.
Variables are fundamental to programming, allowing developers to store,
manipulate, and retrieve data dynamically.
Without variables, programming would be a rigid, inflexible process, unable
to adapt to dynamic data or user input.
Characteristics of Variables
Variables have names, types, and values.
Name – Label or identifier of the symbol.
• The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C is case-sensitive. Variables cannot use
reserved keywords as variable names.
Type – Determines the value that can be assigned the symbol.
• Each variable has a defined data type (e.g., int, float, char) that determines the
kind of data it can hold and the operations that can be performed on it.
Value – The value of the symbol at a given moment.
Characteristics of Variables
Memory Association: A variable is associated with a specific memory
address where its value is stored.
When the variable’s name (or identifier) is used in the program, the information at
the address of the variable is accessed.
The memory size allocated for the variable depends on its type, which must be set
when the variable is declared.
VARIABLE INITIALISATION
Syntax For Declaring Variables
In C, variables are declared using the following syntax
type variable_name;
For instance
int grade;
Variables can be initialized at the time of declaration. The syntax is as follows;
type variable_name = value;
For instance
Int grade = 50;
Variable Initialization
Variable Initialization is the process of assigning an initial value to a variable
at the time of its declaration.
This ensures that the variable has a known value when it is first used,
preventing unexpected behaviour due to garbage values.
The basic syntax data_type variable_name = initial_value;
Methods of Initialization
Direct Initialization
Assigning a value to a variable at the point of declaration using the assignment
operator =
int age = 25;
float pi = 3.14159;
char initial = 'J';
You can also initialize multiple variables of the same type in one line
int x = 1, y = 2, z = 3;
Methods of Initialization
Initialization with Expressions
Using expressions to calculate the initial value.
int width = 10;
int height = 5;
int area = width * height; // area is initialized with an expression
Initialization during Declaration of Arrays
Providing initial values within curly braces {} when declaring an array.
int numbers[5] = {1, 2, 3, 4, 5};
char message[] = "Hello"; // String literal initialization
Methods of Initialization
Initialization of Structures
Providing values for structure members in order, within curly braces.
struct Point {
int x;
int y;
};
struct Point p1 = {10, 20}; // Initialize x with 10 and y with 20
Examples of Variables
int age; Declares an integer variable named age.
float temperature; Declares a single-precision floating-point variable named
temperature.
double pi = 3.14159;: Declares a double-precision floating-point variable
named pi and initializes it with the value 3.14159. double provides more
precision than float.
char initial;: Declares a character variable named initial. It can store a single
character (e.g., 'a', 'Z', '7’).
What to Avoid When Declaring
Variables
Single-letter or Very Short, Uninformative Names
i, j, k: While often acceptable as loop counters in small, localized loops, using them
for other variables makes it hard to understand their purpose
Names That Don't Reflect the Variable's Purpose
total: If it stores the average and flag: If it's used to store a count.
Overly Long and Verbose Names
int thisVariableStoresTheNumberOfPointsEachTeamHas: While descriptiveness is
good, extreme length can hinder readability.
What to Avoid When Declaring
Variables
Names That Use Mixed Case Without a Clear Convention (inconsistency)
totalRecords and total_records in the same codebase.
numberOfRecords and numberofrecords.
Names That Shadow Standard Library Functions or Keywords
printf: Using this as a variable name will conflict with the standard output function.
Variable Scopes
Variable Scopes
C supports various types of variables based on their scope, storage
duration, and purpose. The two types of scopes are;
Local
Global
Local Variables are declared inside a function or block and are accessible
only within that scope.
Global Variables are declared outside all functions and are accessible
throughout the program.
Local Scope
The local scope refers to the region inside a block or a function. It is the
space enclosed between the { } braces.
The variables declared within the local scope are called local variables.
Local variables are visible in the block they are declared in and other blocks
nested inside that block.
Local scope is also called Block scope.
Local variables have no linkage.
Local Variables
They are created upon entering the function and destroyed upon exiting it.
For example:
void function(){
int localVariable = 30; // local variable declaration
printf("%d", localVariable);
}
Local Scope Example
// C program to illustrate the scope of printf("%d", var);
a variable
return 0;
#include <stdio.h>
}
int main()
{
// function where we try to access
the var defined in main()
// Scope of this variable is within
main() function void func() { printf("%d", var); }
int var = 97;
Global scope
The global scope refers to the region outside any block or function.
The variables declared in the global scope are called global variables.
Global variables are visible in every part of the program.
Global is also called File Scope, as the scope of an identifier starts at the
beginning of the file and ends at the end of the file.
Global
Variables
Global variables are
declared outside any
function, usually at the top
of the program.
They can be accessed by
any function within the
program.
Global Scope Example
int main()
# include <stdio.h> {
// variable declared in global scope printf("Before change within main: ");
int global = 5; display();
// global variable accessed from
// changing value of global
within a function
// variable from main function
void display()
printf("After change within main: ");
{
global = 10;
printf("%d\n", global); display();
} }
//main function
VARIABLE
STORAGE CLASSES
Storage Classes
Storage classes define the memory location, lifetime, scope (visibility), and default
initial value of variables.
They specify how long a variable exists in memory and how it can be accessed
within a program.
C provides the following four storage classes
auto
Register
Static
extern.
Auto Storage Class
The auto storage class in C is used to declare variables with automatic storage
duration- it is the default storage class for local variables.
This means that the variable's memory is allocated when the block in which it is declared is
entered, and deallocated when the block is exited.
By default, all local variables inside functions are of the auto storage class, so
explicitly using the auto keyword is rare in practice
Auto Storage Class
A variable can be declared using the auto storage class using the following syntax
auto type variable_name;
#include <stdio.h>
int main() {
auto int num = 105; // 'auto' is optional here as it's the default for local variables
printf("%d\n", num); // Output: 105
return 0;
}
Register Storage Class
The register storage class suggests to the compiler that a particular local
variable should be stored in a CPU register instead of RAM.
This is intended to optimize access speed, but it is just a suggestion and not
a guarantee.
The register keyword can only be used for local variables.
Register Storage Class
Using register is only a suggestion; the compiler may ignore it based on
hardware constraints or optimization decisions. Modern compilers often make
their own choices about register allocation.
The scope is local to the block or function where it is declared, just like auto
variables. The variable exists only during the execution of the block or
function in which it is declared
No default initialization; contains garbage value if not explicitly initialized.
Here is how a variable can be declared using the register storage class
register type variable_name;
Register Storage Class
#include <stdio.h>
int main() {
register int count;
for (count = 0; count < 5; count++) {
printf("%d ", count);
return 0;
}
Static Storage Classes
The static storage class is used to maintain the value of a variable across
function calls.
A static variable retains its value even after the function in which it is declared
finishes executing.
static variables are initialized only once, and their lifetime is the entire program runtime.
The static storage class is used to extend the lifetime of a variable or function so
that it persists for the entire duration of the program, rather than being created
and destroyed each time its block is entered or exited
Here is how a variable can be declared using the static storage class:
static type variable_name;
Static Storage Class
Static variables are initialized only once and exist until the end of the program.
Their value is preserved between function calls, unlike auto variables, which are destroyed when the
block ends.
When declared inside a function or block, the variable is accessible only within that function
or block, but its value persists across multiple invocations.
Static variables are automatically initialized to zero (or NULL for pointers) if not explicitly
initialized.
Static variables are stored in a special area of memory called the data segment, not on the
stack.
Functions can also be declared as static, restricting their visibility to the file in which they are defined
Static Storage Class
#include <stdio.h> int main() {
counter(); // Output: Count: 1
void counter() { counter(); // Output: Count: 2
static int count = 0; // This variable counter(); // Output: Count: 3
retains its value across function calls
return 0;
count++;
}
printf("Count: %d\n", count);
}
Extern Storage Class
The extern storage class helps declare a variable that is defined in another
file or elsewhere in the program. It tells the compiler that the variable exists,
but its definition will be provided later. It is used for sharing variables
between files.
It enables sharing of global variables across multiple source files
Here is how a variable can be declared using the extern storage class:
extern type variable_name;
External Variables
External variables (also known as global variables with external
linkage) are variables that are declared outside of any function and are
intended to be accessible (referenced) from multiple source files within a
project.
Declaring an external variable informs the compiler that a variable with a
specific name and type exists and is defined in some other source file.
Declarations do not allocate storage.
You can have multiple declarations of the same external variable in different source
files.
Extern Storage Class
An extern variable can be accessed from any file that declares it with the
extern keyword.
The variable’s lifetime lasts during the entire duration of the program (static
storage duration).
The variable is visible across different files (translation units).
The default initialization is Zero if the variable is not explicitly initialized.
The purpose of the extern storage class is to reference a global variable or
function defined in another file, without allocating new storage.
External Variables
Define the variable in one source file
// file1.c
int globalCounter = 0; // Definition and initialization
Declare the variable in other source files: In any other source file where you want to use the
globalCounter variable, you need to declare it using the extern keyword
// file2.c
#include <stdio.h>
extern int globalCounter; // Declaration
void incrementAndPrint() {
globalCounter++;
printf("Counter in file2: %d\n", globalCounter);
}
External Variables
// main.c
#include <stdio.h>
extern int globalCounter; // Declaration
int main() {
printf("Initial counter in main: %d\n", globalCounter);
incrementAndPrint(); // Function from file2.c
printf("Counter in main after increment: %d\n", globalCounter);
return 0;
}
Extern Storage Class
// file1.c // file2.c
#include <stdio.h> extern int count; // Declaration of
count from file1.c
int count = 10; // Definition of count
int main() {
void display() { display(); // Output: Count: 10
printf("Count: %d\n", count); return 0;
} }
THE END