C++ Variables

Storing and managing data in your C++ programs

📦 What are C++ Variables?

Variables are containers that store data values in your program. Think of them as labeled boxes where you can put different types of information like numbers, text, or true/false values.


#include <iostream>
using namespace std;

int main() {
    int age = 25;           // Integer variable
    string name = "John";   // String variable
    double price = 19.99;   // Double variable
    
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Price: $" << price << endl;
    
    return 0;
}
                                    

Output:

Name: John
Age: 25
Price: $19.99

Variable Concepts

🏷️

Declaration

Creating a variable with a name

int number;        // Declare
string message;    // Declare
📝

Initialization

Giving a variable its first value

int number = 42;      // Initialize
string message = "Hi"; // Initialize
🔄

Assignment

Changing a variable's value

number = 100;         // Assign new value
message = "Hello";    // Assign new value
📋

Rules

Variable naming guidelines

int myAge;      // Good: camelCase
int my_score;   // Good: snake_case
// int 2names;  // Bad: starts with number

🔹 Creating Variables

Variable creation involves specifying a type, an identifier (name), and optionally an initializer. Syntax: type identifier = value; or type identifier{value}; (preferred, as it prevents narrowing). Initialization is crucial—uninitialized variables hold indeterminate values, leading to undefined behavior. Use auto for type inference when the type is verbose or obvious from the initializer. Choose meaningful names following naming conventions (e.g., camelCase or snake_case) to enhance code readability and maintainability.

#include <iostream>
using namespace std;

int main() {
    // Declaration and initialization
    int studentCount = 30;
    double temperature = 98.6;
    char grade = 'A';
    bool isActive = true;
    string courseName = "C++ Programming";
    
    // Display the values
    cout << "Course: " << courseName << endl;
    cout << "Students: " << studentCount << endl;
    cout << "Temperature: " << temperature << "°F" << endl;
    cout << "Grade: " << grade << endl;
    cout << "Active: " << isActive << endl;
    
    return 0;
}

Output:

Course: C++ Programming
Students: 30
Temperature: 98.6°F
Grade: A
Active: 1

🔹 Variable Naming Rules

C++ variable names must start with a letter or underscore, contain only letters, digits, or underscores, and cannot be keywords. Names are case-sensitive. Follow a consistent naming style: camelCase for variables, PascalCase for types, UPPER_SNAKE_CASE for constants. Descriptive names like studentCount are better than sc. Avoid single letters except for loop counters. Good naming acts as documentation, making code self-explanatory and reducing the need for excessive comments.

Naming Rules:

  • Start with letter or underscore: Not with numbers
  • Use letters, numbers, underscores: No spaces or special characters
  • Case sensitive: 'age' and 'Age' are different
  • No keywords: Can't use 'int', 'return', 'if', etc.
// Valid variable names
int age;
int student_count;
int myScore;
int _private;
int number1;

// Invalid variable names
// int 2names;     // Starts with number
// int my-score;   // Contains hyphen
// int my score;   // Contains space
// int int;        // Reserved keyword

🔹 Multiple Variables

Declare multiple variables of the same type in one statement by separating identifiers with commas. Example: int x = 5, y = 10, sum;. However, this can reduce readability, especially with complex initializers. For clarity, many style guides recommend one declaration per line, each with its own initialization. This practice avoids confusion and makes debugging easier. Note that pointer and reference declarators bind to the individual name: int* p, q; declares p as pointer, q as plain int.

#include <iostream>
using namespace std;

int main() {
    // Multiple variables of same type
    int x = 5, y = 10, z = 15;
    
    // Or declare separately
    double length, width, height;
    length = 10.5;
    width = 8.2;
    height = 6.7;
    
    // Calculate and display
    int sum = x + y + z;
    double volume = length * width * height;
    
    cout << "Sum: " << sum << endl;
    cout << "Volume: " << volume << endl;
    
    return 0;
}

Output:

Sum: 30
Volume: 577.17

🧠 Test Your Knowledge

Which is a valid variable name in C++?