C++ Lesson 2: Unlocking Variables

In the previous lesson, we implemented the “output function” in C++ by printing text, adding comments, and inserting line breaks. However, a program that only repeats fixed content is of little practical use—like a calculator that only displays “Hello, World!”. The introduction of variables addresses this issue. Variables can be understood as small “containers” or “boxes” within a program that can store numbers, text, and even boolean values like “true/false”. By changing the content inside the “box”, the program can immediately become flexible and responsive.

1: The 4 Most Common Variable Types

C++ Lesson 2: Unlocking Variables

If we compare variables to labeled “jars”, different “jars” can hold different types of data (integers, decimals, text, true/false answers). Here are the 4 most commonly used variable types in C++: a) int (Integer Type) Purpose: Store integers (e.g., counting the number of cookies). Importance: A core type for everyday counting and simple mathematical operations. In most modern systems, the range is approximately -2 billion to +2 billion.

#include <iostream>
using namespace std;
int main() {
    // Data type is int, variable name is apples, assigned value is 5
    int apples = 5;
    cout << "I have " << apples << " apples\n";
    return 0;
}

b) float & double (Floating Point Type, i.e., Decimal) float: Stores decimal data (e.g., weighing an object), with medium precision. double: Similar to float but can store more decimal places (e.g., meeting scientific calculation precision requirements).

#include <iostream>
using namespace std;
int main() {
    float temperature = 36.5f;  // f indicates this value is of float type
    double preciseValue = 3.1415926535;
    cout << "Temp: " << temperature << "\nPi: " << preciseValue << "\n";
    return 0;
}

c) bool (Boolean Type) Purpose: Store “true” or “false”, suitable for determining “yes/no” questions (e.g., whether a task is completed). Note: When outputting, false will display as 0, and true will display as 1.

#include <iostream>
using namespace std;
int main() {
    bool isRaining = false;
    cout << "Is it raining? " << isRaining << "\n";  // Output will be 0
    return 0;
}

d) string (String Type) Purpose: Store text, sentences, and other textual data (e.g., names, message content).

Note: Using the string type requires including the header file <string>.

#include <iostream>
#include <string>  // Include the header file required for string type
using namespace std;
int main() {
    string message = "Hello, C++ world!";
    cout << message << "\n";
    return 0;
}

Understanding these 4 types is like knowing your ingredients before cooking—once you master them, you can flexibly combine them to write powerful dynamic programs.

2: Declaring, Assigning, and Modifying Variables

After understanding the main data types, let’s learn how to create and use variables in C++. This process can be likened to: labeling the “box” (declaring the variable) → putting something in the “box” (assigning a value). In C++, there are two common ways to create variables:

a) Declare first, then assign

#include <iostream>
using namespace std;
int main() {
    int age;  // Step 1: Declare the variable (create an empty box named "age")
    age = 20; // Step 2: Assign a value (put 20 in the "age" box)
    cout << "Age: " << age << "\n";
    return 0;
}

b) Declare and assign in one step

#include <iostream>
using namespace std;
int main() {
    int age = 20;  // Simultaneously complete "variable declaration" and "assignment"
    cout << "Age: " << age << "\n";
    return 0;
}

c) Modifying variable values

The core feature of a variable is “modifiable”—it is not fixed after creation.

#include <iostream>
using namespace std;
int main() {
    int age = 20;
    cout << "Initial age: " << age << "\n";  // Initial value: 20
    age = 25;  // Modify the variable value
    cout << "New age: " << age << "\n";      // After modification: 25
    return 0;
}

Output: Initial age: 20New age: 25

Comparison: How does Python handle variables? Python’s variable rules are more flexible than C++: there is no need to declare the type in advance; you can directly write the variable name and assign a value.

name = "Adam"
age = 20
print("name: ", name)
print("Age:", age)
# Modify variable values
name = "Kevin"
age = 25
print("name: ", name)
print("New Age:", age)

Output: name: AdamAge: 20name: KevinNew Age: 25

Core Differences:

C++: Must declare the variable type first (e.g., int, string). Python: Automatically recognizes the type based on the assigned content.

3: Best Practices for Variable Naming

Good variable names make code more readable (for yourself and others). It’s like labeling a “jar” clearly—no one wants to open a jar labeled “x” only to find cookies inside.

Recommended Practices:

a) Use meaningful names (self-explanatory).

int age = 25; // Clear: represents “age”
string userName = “Rahul”; // Clear: represents “username”

b) Use camelCase or snake_case to enhance readability.

c) Names should be “short yet descriptive” (avoid being too long or too short).

Avoid Practices:

a) Naming with meaningless characters (syntactically correct but poor readability):int x = 25; // ✅ Syntactically valid, but cannot determine what “x” represents

b) Starting with a number:int 1stUser = 10; // ❌ Syntactically invalid

c) Using special characters or spaces:string user-name = “Rahul”; // ❌ Syntactically invalid (contains “-“)

d) Using C++ keywords (e.g., int, return, class, etc.).

Conclusion

In this lesson, we unlocked the core building blocks of a program—variables. The content includes: 1. 4 core data types (int, float/double, bool, string); 2. Methods for declaring, assigning, and modifying variables; 3. Differences in variable handling between C++ and Python; 4. Best practices for variable naming. Mastering variables allows programs to achieve the functionality of “storing, modifying, and processing information”, truly gaining dynamism and practical value.

Leave a Comment