C++ Variables and Data Types
If you’re new to C++, one of the first things you’ll come across is variables and data types. Don’t worry — this post will explain these concepts in the simplest way possible, just like I wish someone had explained to me when I started learning programming.
Let’s break it down.
🧠 What is a Variable?
A variable is like a container in your computer’s memory. You use it to store information that your program can use later.
Think of it like a lunchbox. You label it with a name, and you put some food (data) inside. When you’re hungry (need the value), you open the box and eat what’s inside.
In C++, here’s how you declare a variable:
cpp int age = 21;
This line means:
-
int
is the type of data (we’re storing a number). -
age
is the name of the variable. -
21
is the value we’re putting inside it.
📦 Common Data Types in C++
C++ is a strongly typed language, meaning you must tell it what kind of data you’re storing.
Here are some basic ones:
Data Type | Example | What It Stores |
---|---|---|
int |
int marks = 85; |
Whole numbers (positive or negative) |
float |
float weight = 55.5; |
Decimal numbers |
double |
double pi = 3.14159; |
More precise decimal numbers |
char |
char grade = 'A'; |
A single character |
string |
string name = "Aman"; |
A group of characters (text) |
bool |
bool isPassed = true; |
True or false |
Note: To use string
, you need to include this at the top of your code:
#include <string>
🔧 Declaring and Using Variables
Here’s a small C++ program using different data types:
#include <iostream>
#include <string>
using namespace std;
int main() {
int age = 21;
float weight = 55.5;
char grade = ‘A’;
string name = “Aman”;
bool isStudent = true;
cout << “Name: ” << name << endl;
cout << “Age: ” << age << endl;
cout << “Weight: ” << weight << endl;
cout << “Grade: ” << grade << endl;
cout << “Is a student? ” << isStudent << endl;
return 0;
}
Output:
vbnet Name: Aman
Age: 21
Weight: 55.5
Grade: A
Is a student? 1
⚠️ Quick Tips for Beginners
-
Use meaningful names: Instead of
x
ory
, useage
,price
,totalMarks
etc. -
Case sensitive:
Age
andage
are not the same in C++. -
Initialize your variables: Don’t forget to give them a value before using.