Simple Variables
Programs need to store information, and variables are the basic units for storing information. When declaring a variable, three basic attributes must be specified: storage location, stored value, and data type.
Basic Concepts
#include <iostream>
using namespace std;
int main() {
// Variable declaration and initialization
int braincount; // Declare an integer variable
braincount = 5; // Assign a value to the variable
cout << "braincount's value: " << braincount << endl;
cout << "braincount's memory address: " << &braincount << endl;
return 0;
}
Variable Naming Rules
Examples of Correct Variable Names
#include <iostream>
#include <string>
using namespace std;
int main() {
// Examples of valid variable names
int age; // Clear and straightforward
double salary; // Descriptive name
string student_name; // Using underscores
string firstName; // Camel case
int item_count_2024; // Contains numbers
double _internal_temp; // Starts with an underscore (use with caution)
// Variable assignment
age = 25;
salary = 50000.50;
student_name = "Zhang San";
firstName = "Li Si";
item_count_2024 = 100;
_internal_temp = 36.5;
// Output variable values
cout << "Age: " << age << endl;
cout << "Salary: " << salary << endl;
cout << "Student Name: " << student_name << endl;
cout << "First Name: " << firstName << endl;
cout << "2024 Item Count: " << item_count_2024 << endl;
cout << "Internal Temperature: " << _internal_temp << endl;
return 0;
}
Detailed Explanation of Variable Naming Rules
#include <iostream>
using namespace std;
int main() {
// ✅ Valid variable names
int validVariable; // Starts with a letter
int valid_variable; // Uses underscore
int variable123; // Contains numbers, but not at the start
int _tempVariable; // Starts with an underscore (not recommended for global use)
int Var123_abc; // Mixed usage
// ❌ Invalid variable names (commented out because they will cause compilation errors)
// int 123variable; // Error: starts with a number
// int my-variable; // Error: contains hyphen
// int variable@name; // Error: contains special character
// int double; // Error: uses keyword
// int class; // Error: uses keyword
// Meaningful variable name examples
double monthly_salary = 8000.50;
int days_in_week = 7;
string company_name = "Tech Corp";
bool is_employee_active = true;
const double PI = 3.14159; // Constants use uppercase
cout << "Monthly Salary: $" << monthly_salary << endl;
cout << "Days in Week: " << days_in_week << endl;
cout << "Company Name: " << company_name << endl;
cout << "Is Employee Active: " << (is_employee_active ? "Yes" : "No") << endl;
cout << "Pi: " << PI << endl;
return 0;
}
Comparison of Naming Styles
#include <iostream>
using namespace std;
int main() {
// Different naming styles
// 1. Snake case
int student_age = 20;
string course_name = "Computer Science";
double average_grade = 85.5;
// 2. Camel case
int studentAge = 20;
string courseName = "Computer Science";
double averageGrade = 85.5;
// 3. Pascal case - usually for class names
class StudentRecord {
public:
string studentName;
int studentAge;
};
// 4. Constant naming - usually all uppercase
const int MAX_STUDENTS = 100;
const double TAX_RATE = 0.15;
const string COMPANY_NAME = "ABC Corporation";
cout << "Snake case example:" << endl;
cout << "Student Age: " << student_age << endl;
cout << "Course Name: " << course_name << endl;
cout << "Average Grade: " << average_grade << endl;
cout << "\nCamel case example:" << endl;
cout << "Student Age: " << studentAge << endl;
cout << "Course Name: " << courseName << endl;
cout << "Average Grade: " << averageGrade << endl;
cout << "\nConstant example:" << endl;
cout << "Max Students: " << MAX_STUDENTS << endl;
cout << "Tax Rate: " << TAX_RATE << endl;
cout << "Company Name: " << COMPANY_NAME << endl;
return 0;
}
Practical Application Examples
#include <iostream>
#include <cmath> // For mathematical calculations
using namespace std;
int main() {
// Variable naming example in e-commerce applications
// Product information
string product_name = "Wireless Bluetooth Headphones";
double product_price = 299.99;
int quantity_in_stock = 50;
bool is_product_available = true;
// Order information
int order_id = 1001;
string customer_name = "Wang Xiaoming";
string shipping_address = "1 Zhongguancun Street, Haidian District, Beijing";
double order_total = 0.0;
// Calculate order total
int quantity_ordered = 2;
double discount_rate = 0.1; // 10% discount
double tax_rate = 0.08; // 8% tax
order_total = product_price * quantity_ordered;
double discount_amount = order_total * discount_rate;
double subtotal = order_total - discount_amount;
double tax_amount = subtotal * tax_rate;
double final_total = subtotal + tax_amount;
// Display order details
cout << "=== Order Details ===" << endl;
cout << "Order ID: #" << order_id << endl;
cout << "Customer: " << customer_name << endl;
cout << "Product: " << product_name << endl;
cout << "Unit Price: ¥" << product_price << endl;
cout << "Quantity: " << quantity_ordered << endl;
cout << "Total Product Price: ¥" << order_total << endl;
cout << "Discount Amount: ¥" << discount_amount << endl;
cout << "Subtotal: ¥" << subtotal << endl;
cout << "Tax: ¥" << tax_amount << endl;
cout << "Final Total: ¥" << final_total << endl;
// Update stock
quantity_in_stock -= quantity_ordered;
if (quantity_in_stock <= 0) {
is_product_available = false;
}
cout << "\n=== Stock Update ===" << endl;
cout << "Remaining Stock: " << quantity_in_stock << endl;
cout << "Is Product Available: " << (is_product_available ? "Yes" : "No") << endl;
return 0;
}
Variable Scope Example
#include <iostream>
using namespace std;
// Global variable (use with caution)
int global_counter = 0;
void demonstrate_scope() {
// Local variable
int local_variable = 10;
static int static_variable = 0; // Static local variable
local_variable++;
static_variable++;
global_counter++;
cout << "Local Variable: " << local_variable << endl;
cout << "Static Variable: " << static_variable << endl;
cout << "Global Variable: " << global_counter << endl;
}
int main() {
cout << "First Call to Function:" << endl;
demonstrate_scope();
cout << "\nSecond Call to Function:" << endl;
demonstrate_scope();
cout << "\nThird Call to Function:" << endl;
demonstrate_scope();
// Cannot access local_variable from main function
// cout << local_variable; // Error!
return 0;
}
Summary of Best Practices for Variable Naming
-
Use meaningful names: Variable names should clearly express their purpose
-
Maintain consistency: Use the same naming conventions throughout the project
-
Avoid abbreviations: Unless they are widely recognized abbreviations (e.g.,
<span>id</span>,<span>max</span>,<span>min</span>) -
Use correct naming styles:
- Snake case:
<span>variable_name</span> - Camel case:
<span>variableName</span> - Pascal case:
<span>VariableName</span>(mainly for classes) - Constants:
<span>CONSTANT_NAME</span>
Avoid using reserved names:
- Do not start with double underscores:
<span>__reserved</span> - Do not start with a single underscore followed by an uppercase letter:
<span>_Reserved</span> - Use caution with single underscore at the beginning:
<span>_variable</span>
Good variable naming can make code more readable and maintainable, which is an important foundational skill in programming.