#C++ Comments
#Overview
Comments are text descriptions in code used to explain the purpose, functionality, and implementation details of the code. Compilers ignore comment content; they are only used to improve code readability and maintainability. Good commenting habits are an important sign of professional programming.
#📝 Comment Types
#Single-Line Comments
#include <iostream>
int main() {
// This is a single-line comment
int age = 25; // Variable declaration and initialization
std::cout << "Hello World" << std::endl; // Output statement
// Calculate circle area
double radius = 5.0;
double area = 3.14159 * radius * radius; // Area formula: π * r²
return 0; // Function return value
}#Multi-Line Comments
/*
* This is an example of multi-line comments
* Can span multiple lines
* Usually used for longer descriptions
*/
#include <iostream>
/*
* Function name: calculateArea
* Functionality: Calculate rectangle area
* Parameters: length - length, width - width
* Return value: Rectangle area
*/
double calculateArea(double length, double width) {
/*
* Area calculation formula
* Area = Length × Width
*/
return length * width;
}
/* Main function */
int main() {
double length = 10.0; /* Rectangle length */
double width = 5.0; /* Rectangle width */
/* Call function to calculate area */
double area = calculateArea(length, width);
/* Output result */
std::cout << "Rectangle area: " << area << std::endl;
return 0;
}#Nested Comment Issues
// Note: C++ multi-line comments cannot be nested
/*
* This is outer comment
/* This inner comment will cause problems */
* Because the first */ will end the entire comment block
*/
// Correct approach is to use single-line comments to "comment out" code containing multi-line comments
// /*
// * This way you can safely comment out multi-line comments
// * Won't have nesting problems
// */
// Or use preprocessor directives
#if 0
/*
* This code block will not be compiled
* Can contain any type of comments
*/
int unused_function() {
// These codes will not be compiled
return 42;
}
#endif#🎨 Comment Styles and Best Practices
#File Header Comments
/**
* @file: calculator.cpp
* @author: Zhang San
* @date: 2024-01-15
* @version: 1.0
* @description: Simple calculator program, providing basic mathematical operation functions
* @copyright: Copyright (c) 2024
*/
#include <iostream>
#include <cmath>
/**
* @brief Calculator class
*
* Provides basic mathematical operations including addition, subtraction,
* multiplication, division, and power operations
*/
class Calculator {
public:
/**
* @brief Addition operation
* @param a First operand
* @param b Second operand
* @return Sum of two numbers
*/
static double add(double a, double b) {
return a + b;
}
/**
* @brief Division operation
* @param dividend Dividend
* @param divisor Divisor
* @return Division result
* @throws std::invalid_argument Throws exception when divisor is 0
*/
static double divide(double dividend, double divisor) {
if (divisor == 0) {
throw std::invalid_argument("Divisor cannot be zero");
}
return dividend / divisor;
}
};#Function Comments
#include <vector>
#include <algorithm>
/**
* @brief Search for target value in array
*
* Uses linear search algorithm to find the specified target value in array.
* Time complexity: O(n), Space complexity: O(1)
*
* @param arr Array to search
* @param target Target value
* @return Returns its index if target found; otherwise returns -1
*
* @example
* std::vector<int> numbers = {1, 3, 5, 7, 9};
* int index = linearSearch(numbers, 5); // Returns 2
*/
int linearSearch(const std::vector<int>& arr, int target) {
// Iterate through each element in the array
for (size_t i = 0; i < arr.size(); ++i) {
// If target value is found, return index
if (arr[i] == target) {
return static_cast<int>(i);
}
}
// Target value not found
return -1;
}
/**
* @brief Quick sort algorithm implementation
*
* Recursively implemented quick sort algorithm with average time complexity O(n log n)
*
* @param arr Array to sort (will be modified)
* @param low Starting index of sorting range
* @param high Ending index of sorting range
*
* @pre low >= 0 && high < arr.size()
* @post arr[low..high] is sorted in ascending order
*/
void quickSort(std::vector<int>& arr, int low, int high) {
if (low < high) {
// Partition operation, get correct position of pivot element
int pivot = partition(arr, low, high);
// Recursively sort elements left of pivot
quickSort(arr, low, pivot - 1);
// Recursively sort elements right of pivot
quickSort(arr, pivot + 1, high);
}
}#Class and Member Comments
/**
* @brief Bank account class
*
* Simulates basic bank account operations including deposits, withdrawals,
* and balance queries. Ensures safety and data integrity of account operations
*/
class BankAccount {
private:
std::string accountNumber_; ///< Account number
std::string ownerName_; ///< Account holder name
double balance_; ///< Account balance
bool isActive_; ///< Whether account is active
/**
* @brief Validate transaction amount validity
* @param amount Transaction amount
* @return Returns true if amount is valid, otherwise returns false
*/
bool isValidAmount(double amount) const {
return amount > 0 && amount <= 1000000; // Single transaction limit 1 million
}
public:
/**
* @brief Constructor
* @param accountNumber Account number
* @param ownerName Account holder name
* @param initialBalance Initial balance (default 0)
*/
BankAccount(const std::string& accountNumber,
const std::string& ownerName,
double initialBalance = 0.0)
: accountNumber_(accountNumber)
, ownerName_(ownerName)
, balance_(initialBalance)
, isActive_(true) {
// Validate initial balance
if (initialBalance < 0) {
throw std::invalid_argument("Initial balance cannot be negative");
}
}
/**
* @brief Deposit operation
*
* Deposits specified amount into account, updates account balance
*
* @param amount Deposit amount, must be greater than 0
* @return Returns true if operation succeeds, false if fails
*
* @warning Single deposit amount cannot exceed 1 million
*/
bool deposit(double amount) {
// Check account status
if (!isActive_) {
std::cerr << "Account frozen, cannot perform deposit operation" << std::endl;
return false;
}
// Validate deposit amount
if (!isValidAmount(amount)) {
std::cerr << "Invalid deposit amount" << std::endl;
return false;
}
// Execute deposit operation
balance_ += amount;
std::cout << "Deposit successful, current balance: " << balance_ << std::endl;
return true;
}
/**
* @brief Withdrawal operation
*
* @param amount Withdrawal amount
* @return Returns true if operation succeeds, false if fails
*
* @note Withdrawal amount cannot exceed current balance
*/
bool withdraw(double amount) {
// Check account status
if (!isActive_) {
std::cerr << "Account frozen, cannot perform withdrawal operation" << std::endl;
return false;
}
// Validate withdrawal amount
if (!isValidAmount(amount)) {
std::cerr << "Invalid withdrawal amount" << std::endl;
return false;
}
// Check if balance is sufficient
if (amount > balance_) {
std::cerr << "Insufficient balance, current balance: " << balance_ << std::endl;
return false;
}
// Execute withdrawal operation
balance_ -= amount;
std::cout << "Withdrawal successful, current balance: " << balance_ << std::endl;
return true;
}
/**
* @brief Get account balance
* @return Current account balance
*/
double getBalance() const {
return balance_;
}
};#📋 Documentation Generation Comments (Doxygen)
#Doxygen Tags
/**
* @brief Math utility class
* @details Provides common mathematical calculation functions including basic operations,
* trigonometric functions, logarithmic functions, etc.
* @author Li Si
* @date 2024-01-15
* @version 2.1.0
* @since 1.0.0
* @todo Add more advanced mathematical functions
* @bug May overflow with very large values
* @warning Some functions may throw exceptions
*/
class MathUtils {
public:
/**
* @brief Calculate greatest common divisor of two numbers
*
* @param a First integer
* @param b Second integer
* @return int Greatest common divisor
*
* @par Algorithm
* Uses Euclidean algorithm (successive division)
*
* @par Example
* @code
* int gcd = MathUtils::gcd(48, 18); // Returns 6
* @endcode
*
* @see lcm()
* @since 1.0.0
*/
static int gcd(int a, int b) {
// Recursive implementation of Euclidean algorithm
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
/**
* @brief Calculate least common multiple of two numbers
*
* @param a First integer
* @param b Second integer
* @return int Least common multiple
*
* @note Uses formula: lcm(a,b) = (a * b) / gcd(a,b)
*
* @see gcd()
* @since 1.0.0
*/
static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
/**
* @brief Check if a number is prime
*
* @param n Number to check
* @return true If number is prime
* @return false If number is not prime
*
* @par Time Complexity
* O(√n)
*
* @par Space Complexity
* O(1)
*
* @pre n > 0
* @post Return value correctly indicates whether n is prime
*
* @exception std::invalid_argument Throws when n <= 0
*/
static bool isPrime(int n) {
if (n <= 0) {
throw std::invalid_argument("Input must be a positive integer");
}
if (n <= 1) return false; // 0 and 1 are not prime
if (n <= 3) return true; // 2 and 3 are prime
if (n % 2 == 0 || n % 3 == 0) return false; // Exclude multiples of 2 and 3
// Check 5, 7, 11, 13, ...
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
};#Conditional Compilation Comments
#include <iostream>
// Debug macro definition
#ifdef DEBUG
#define DBG_PRINT(x) std::cout << "DEBUG: " << x << std::endl
#else
#define DBG_PRINT(x) // Empty in non-debug mode
#endif
/**
* @brief Demonstrate use of conditional compilation
*/
void demonstrateConditionalCompilation() {
int value = 42;
// Debug info only outputs in DEBUG mode
DBG_PRINT("The value of variable value is: " << value);
#ifdef ENABLE_LOGGING
std::cout << "Logging functionality enabled" << std::endl;
#endif
#ifndef PRODUCTION_BUILD
// Code only in non-production environment
std::cout << "This is development environment debug code" << std::endl;
#endif
// Platform-specific code
#ifdef _WIN32
std::cout << "Running on Windows platform" << std::endl;
#elif defined(__linux__)
std::cout << "Running on Linux platform" << std::endl;
#elif defined(__APPLE__)
std::cout << "Running on macOS platform" << std::endl;
#else
std::cout << "Unknown platform" << std::endl;
#endif
}#🚫 Common Comment Pitfalls
#Bad Comment Examples
// Bad comment examples
// Increment value of i ❌ Obvious comment
i++;
// Set x to 0 ❌ Repeating code content
int x = 0;
// Loop 10 times ❌ Describes implementation rather than purpose
for (int i = 0; i < 10; i++) {
// TODO: Fix this bug ❌ Vague TODO
process(i);
}
/* This function is very important!!! */ ❌ Emotional comment
int importantFunction() {
// There's a hack here ❌ Admits code quality problem without explanation
return 42;
}
// Code written by John, don't modify ❌ Shifting blame
void johnsCode() {
// Some complex logic...
}#Good Comment Examples
// Good comment examples
/**
* @brief Search for elements in sorted array using binary search
*
* Since the array is sorted, we can use binary search to improve efficiency
* Time complexity reduced from O(n) to O(log n)
*/
int binarySearch(const std::vector<int>& arr, int target) {
int left = 0;
int right = arr.size() - 1;
while (left <= right) {
// Midpoint calculation method avoiding integer overflow
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1; // Target in right half
} else {
right = mid - 1; // Target in left half
}
}
return -1; // Target element not found
}
/**
* @brief Calculate the nth term of Fibonacci sequence
*
* Uses dynamic programming method to avoid repeated calculations,
* greatly improving efficiency compared to recursive method
*/
long long fibonacci(int n) {
if (n <= 1) return n;
// Use rolling array to optimize space complexity
long long prev2 = 0; // f(n-2)
long long prev1 = 1; // f(n-1)
long long current = 0;
for (int i = 2; i <= n; i++) {
current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
}
return current;
}
// Business logic: Calculate discount based on user level
// VIP users get 20% discount, regular users get 5% discount
double calculateDiscount(UserLevel level, double amount) {
const double VIP_DISCOUNT = 0.20;
const double REGULAR_DISCOUNT = 0.05;
switch (level) {
case UserLevel::VIP:
return amount * VIP_DISCOUNT;
case UserLevel::Regular:
return amount * REGULAR_DISCOUNT;
default:
return 0.0; // New users no discount
}
}#🛠️ Comment Tools and Tips
#IDE Comment Shortcuts
// Comment shortcuts in most IDEs:
// Visual Studio / VS Code:
// Ctrl + / Single-line comment/uncomment
// Ctrl + Shift + / Multi-line comment/uncomment
// CLion / IntelliJ:
// Ctrl + / Single-line comment/uncomment
// Ctrl + Shift + / Multi-line comment/uncomment
// Comment template example
/**
* @brief ${Function description}
*
* @param ${Parameter name} ${Parameter description}
* @return ${Return value description}
*
* @author ${Author}
* @date ${Date}
*/#Comment Maintenance Suggestions
#include <iostream>
#include <vector>
/**
* @brief Data processing class
* @version 2.0.0
* @changelog
* - v2.0.0: Refactored data processing algorithm, improved performance
* - v1.5.0: Added error handling mechanism
* - v1.0.0: Initial version
*/
class DataProcessor {
private:
std::vector<int> data_;
public:
/**
* @brief Process data
*
* @deprecated This method is deprecated, please use processDataV2()
* @see processDataV2()
*/
[[deprecated("Replace with processDataV2()")]]
void processData() {
// Old processing logic...
}
/**
* @brief New version of data processing method
*
* Improved performance by 50% compared to old version,
* added error handling
*
* @since 2.0.0
*/
void processDataV2() {
// New optimized processing logic...
try {
// Process data...
} catch (const std::exception& e) {
std::cerr << "Data processing error: " << e.what() << std::endl;
}
}
};#Summary
Comments are an important means of code documentation. Good commenting habits include:
#Comment Principles
- Explain why, not what: Comments should explain the purpose and reasons for the code
- Keep comments synchronized with code: Update comments promptly when modifying code
- Avoid obvious comments: Don't comment on self-evident code
- Use consistent style: Team should unify comment format and style
#Comment Type Uses
- Single-line comments (//): Brief descriptions, temporary markers
- *Multi-line comments (/ */)**: Detailed documentation, large sections
- Documentation comments/: API documentation, auto-generated documentation
#Best Practices
- Add explanations before complex algorithms
- Write detailed documentation for public interfaces
- Use standardized documentation formats (like Doxygen)
- Avoid long-term existence of commented-out code
Good comments not only help other developers understand your code, but also help you maintain your own code in the future.