Variables and constants are basic building blocks of C++ programming. They are used to store data that a program can use and process.
What is a Variable?
A variable is a named memory location used to store data. The value of a variable can change during program execution.
Syntax of Variable
data_type variable_name;
Example:
int age;
Initializing a Variable
You can assign a value to a variable during declaration.
int age = 18;
Example Program
#include <iostream>
using namespace std;
int main() {
int age = 18;
cout << age;
return 0;
}
Output
18
Types of Variables
Integer Variable
Stores whole numbers.
int number = 10;
Float Variable
Stores decimal numbers.
float price = 99.5;
Character Variable
Stores single characters.
char grade = 'A';
String Variable
Stores text.
string name = "Ali";
Rules for Naming Variables
- Names can contain letters, digits, and underscore
- Names cannot start with a number
- Spaces are not allowed
- C++ keywords cannot be used
- Variable names are case-sensitive
Valid examples:
int age;
float total_marks;
Invalid examples:
int 2age;
float total marks;
What is a Constant?
A constant is a value that cannot be changed during program execution.
Using const Keyword
const float PI = 3.14;
Example of Constant
#include <iostream>
using namespace std;
int main() {
const int DAYS = 7;
cout << DAYS;
return 0;
}
Output
7
Difference Between Variable and Constant
| Variable | Constant |
|---|---|
| Value can change | Value cannot change |
| Declared normally | Declared using const |
| Used for changing data | Used for fixed values |
Why Variables and Constants are Important
They are important because they:
- Store program data
- Help perform calculations
- Make programs flexible
- Improve code readability
- Manage fixed and changing values efficiently
Real-Life Example
- Variable → Bank balance that changes
- Constant → Number of days in a week
Conclusion
Variables and constants are essential concepts in C++ programming. Variables store changing data, while constants store fixed values. Understanding them helps build a strong foundation for programming and problem-solving.