C++ Variables
Understanding data storage in C++ programming
📦 What are C++ Variables?
Variables in C++ are containers that store data values. They have names, types, and hold information that can be used and modified throughout your program execution.
// This is a simple C++ variable example
int age = 25;
string name = "John";
cout << "Hello " << name << ", you are " << age << " years old!";
Output:
Hello John, you are 25 years old!
Variable Declaration Types
Integer Variables
Store whole numbers
int score = 100;
int lives = 3;
String Variables
Store text and characters
string message = "Hello World";
string username = "player1";
Boolean Variables
Store true or false values
bool isActive = true;
bool gameOver = false;
Modifiable Variables
Values can be changed
int counter = 0;
counter = counter + 1;
🔹 Variable Declaration Syntax
C++ variables must be declared with a type before use:
// Basic variable declaration
int number; // Declare without value
int age = 25; // Declare with initial value
string name = "Alex"; // String variable
double price = 19.99; // Decimal number
// Multiple variables of same type
int x = 10, y = 20, z = 30;
Output:
Variables declared and initialized successfully
🔹 Variable Naming Rules
Follow these rules when naming C++ variables:
// Valid variable names
int playerScore = 100;
string first_name = "John";
double PI_VALUE = 3.14159;
bool isGameRunning = true;
// Invalid variable names (commented out)
// int 2players = 5; // Cannot start with number
// string user-name; // Cannot use hyphens
// bool class = true; // Cannot use keywords
Naming Best Practices:
-
Use descriptive names:
playerHealthinstead ofph - Start with letter or underscore
- Use camelCase or snake_case consistently
-
Avoid C++ keywords like
int,class,return
🔹 Working with Variables
Here's how to use variables in a complete program:
#include <iostream>
#include <string>
using namespace std;
int main() {
// Declare and initialize variables
string playerName = "Hero";
int level = 1;
double experience = 0.0;
bool hasWeapon = false;
// Use variables
cout << "Player: " << playerName << endl;
cout << "Level: " << level << endl;
cout << "Experience: " << experience << endl;
cout << "Has Weapon: " << hasWeapon << endl;
// Modify variables
level = level + 1;
experience = 150.5;
hasWeapon = true;
cout << "\nAfter leveling up:" << endl;
cout << "Level: " << level << endl;
cout << "Experience: " << experience << endl;
cout << "Has Weapon: " << hasWeapon << endl;
return 0;
}
Output:
Player: Hero
Level: 1
Experience: 0
Has Weapon: 0
After leveling up:
Level: 2
Experience: 150.5
Has Weapon: 1