📦 C++ Variables – Declare, Initialize, and Use
Variables are like containers or boxes in your computer’s memory where you store stuff — like names, scores, or even the meaning of life (which is 42, obviously 😄).
🔹 What is a Variable?
A variable:
- Has a name
- Stores a value
- Has a data type
Example: If you say int age = 25;
, you’re creating a variable called age
that stores an integer value 25
.
🧪 Syntax of Variable Declaration
data_type variable_name = value;
You can also declare without assigning a value right away:
data_type variable_name;
🔧 Example: C++ Variable Declaration
#include <iostream> using namespace std; int main() { int age = 25; float height = 5.9; char grade = 'A'; string name = "Alex"; cout << "Name: " << name << endl; cout << "Age: " << age << endl; cout << "Height: " << height << endl; cout << "Grade: " << grade << endl; return 0; }
📌 Common Data Types
Data Type | Use |
---|---|
int |
Stores whole numbers (e.g. 42) |
float |
Stores decimal numbers (e.g. 3.14) |
char |
Stores single characters (e.g. ‘A’) |
string |
Stores text (e.g. “Hello”) |
bool |
Stores true or false |
🧠 Remember
- Variable names must begin with a letter or underscore
- They cannot have spaces or special symbols (except _)
- Use meaningful names like
score
oruserAge