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.
/* * 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;}
// 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
#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); }}
/** * @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; }};
// Bad comment examples// Increment value of i ❌ Obvious commenti++;// Set x to 0 ❌ Repeating code contentint x = 0;// Loop 10 times ❌ Describes implementation rather than purposefor (int i = 0; i < 10; i++) { // TODO: Fix this bug ❌ Vague TODO process(i);}/* This function is very important!!! */ ❌ Emotional commentint importantFunction() { // There's a hack here ❌ Admits code quality problem without explanation return 42;}// Code written by John, don't modify ❌ Shifting blamevoid johnsCode() { // Some complex logic...}
// 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% discountdouble 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 }}
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
Multi-Line Comments
Nested Comment Issues
🎨 Comment Styles and Best Practices
File Header Comments
Function Comments
Class and Member Comments
📋 Documentation Generation Comments (Doxygen)
Doxygen Tags
Conditional Compilation Comments
🚫 Common Comment Pitfalls
Bad Comment Examples
Good Comment Examples
🛠️ Comment Tools and Tips
IDE Comment Shortcuts
Comment Maintenance Suggestions
Summary
Comments are an important means of code documentation. Good commenting habits include:
Comment Principles
Comment Type Uses
Best Practices
Good comments not only help other developers understand your code, but also help you maintain your own code in the future.