C++ Variables – Complete Notes
1. What is a Variable?
A variable in C++ is a named memory location used to store data. The value of a variable can be
changed during program execution.
2. Declaration of Variables
Syntax:
data_type variable_name;
Example:
int age;
3. Initialization of Variables
Initialization means assigning an initial value to a variable at the time of declaration.
Example:
int age = 20;
4. Types of Variables
• Local Variables – Declared inside a function and accessible only within that function.
• Global Variables – Declared outside all functions and accessible throughout the program.
• Static Variables – Retain their value between function calls.
• Automatic Variables – Default local variables that are created and destroyed automatically.
5. Data Types Used with Variables
• int – stores integers (e.g., 10, -5)
• float – stores decimal numbers (e.g., 3.14)
• double – stores large decimal numbers
• char – stores single characters (e.g., 'A')
• bool – stores true or false
6. Rules for Naming Variables
• Variable name must start with a letter or underscore (_).
• It cannot start with a number.
• No spaces are allowed.
• Special characters are not allowed except underscore.
• Variable names are case-sensitive.
7. Example Program
int main() {
int a = 10;
float b = 5.5;
char c = 'X';
return 0;
}