A program needs somewhere to keep the values it works with: marks, totals, counters. These storage places are variables. This section explains how to create them, give them values, and avoid the classic bug of using a variable before it has a value.
What a variable is
The type of a variable never changes after it is declared; only its value does.
Declaring variables
A declaration tells the compiler the name and type of a variable so that memory can be set aside for it:
Syntax
data-type variable-name1, variable-name2, ... ;
Examples: int count;, float length, width;, long population;, char grade;.
Every variable must be declared before it is used. Using an undeclared name is always a compile-time error.
Initialising variables
Initialisation gives a variable its first value. There are two ways:
In the declaration:int a = 10;, float rate = 0.4e-5f;, char grade = 'A';
By a later assignment:int a; then a = 10;
A local variable that is declared but never given a value holds an indeterminate value, often called a garbage value, and reading it is undefined behaviour. Variables declared outside all functions (global variables) are automatically set to zero.
Key takeaways
A variable has a name, a type, a value and an address; only the value changes.
Declare before use: type name;. Undeclared names are compile-time errors.
Initialise in the declaration or by assignment; uninitialised locals hold garbage.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Explain the difference between declaring and initialising a variable, using int total; and int total = 0;.
Show worked answer
int total; is a declaration only: it creates an int variable called total but, inside a function, its value is indeterminate (garbage) until something is assigned. int total = 0; declares the variable and initialises it in the same statement, so it starts with the known value 0. A running total must be initialised to 0 before values are added to it.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/data-types-operators-and-expressions/variables-declaration-and-initialisation/ to read this page.