For working professionals
For fresh graduates
More
Explore C++ Tutorials: Explori…
1. The Ultimate C++ Guide: C++ Tutorial for Beginners
2. Application of C++
3. C++ Hello World Program
4. C++ Variable
5. Reference Variable in C++
6. Function Overloading in C++
7. Functions in C++
8. Pointer in C++
9. Data Types in C++
10. C++ for Loop
11. While Loop in C++
12. C++ Lambda
13. Loop in C++
14. Switch Case in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
18. Class and Object in C++
19. Constructor in C++
20. Copy Constructor in C++
21. Destructor in C++
22. Multiple Inheritance in C++
23. Encapsulation in C++
24. Single Inheritance in C++
25. Friend Class in C++
26. Hierarchical Inheritance in C++
27. Virtual Base Class in C++
28. Abstract Class in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
32. Initialize Vector in C++
33. Iterators in C++
34. Queue in C++
35. Priority Queue in C++
36. Stack in C++
37. ifstream in C++
38. Exception Handling in C++
39. Memory Management in C++
40. Templates in C++
41. Type Conversion in C++
42. Enumeration in C++
43. Namespace in C++
44. Set Precision in C++
45. Stringstream in C++
46. Recursion in C++
47. Random Number Generator in C++
48. C++ Shell
49. Setw in C++
50. Multithreading in C++
51. Atoi in C++
52. Call by Value and Call by Reference in C++
53. Difference Between C and C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
59. Power Function in C++
60. Data Hiding in C++
61. Inline Function in C++
62. Getline Function in C++
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
67. static_cast in C++
68. C++ Comments
Now Reading
69. Structures in C++
70. C++ Standard Template Library (STL)
71. Virtual Function in C++
72. Sorting in C++
73. Polymorphism in C++
74. Oops Concepts in C++
75. Converting Integers to Strings in C++
76. Differences Between Break and Continue
C++ comments are like notes we scribble in the margins of our code, but unlike messy handwriting, these notes are perfectly ignored by the computer.
So, why bother with them? One word, readability.
Comments are like journals, turning complex code into a story that you and other developers can easily follow. Comments also make maintenance easier. Imagine revisiting our own code months later, comments are the memory joggers that help us understand our past decisions.
Also, like many other developers, I believe that comments help us pinpoint problems by temporarily 'switching off' sections of code for testing. Let us learn all about C++ comments.
C++ comments are sections of text within your code that the compiler intentionally ignores during the compilation process. They are designed specifically for human readers.
C++ inherited its commenting style directly from the C programming language, which is its predecessor. The concept of cpp comment has been around since the early days of programming languages. The value of explaining code for human understanding was quickly recognized.
Comments exist to enhance code readability, explain logic, and improve maintainability. They serve as notes for yourself and other developers. Commenting syntax is now standardized, ensuring that comments written in C++ will be interpreted correctly by C++ compilers across different systems.
Here are three key reasons why C++ comments matter:
There are two types of C++ comments. Let us learn about them.
The double-slash (//) marks the beginning of a single-line comment. Everything from the // to the end of the line is disregarded by the compiler.
Example:
int age = 25; // This variable stores the person's age
// Calculate discount based on age
if (age > 60) {
discount = 0.15; // 15% discount for seniors
}
Single line comment in C++ is used for:
A multi-line comment begins with /* and ends with */. Everything enclosed within these markers is ignored, regardless of how many lines it spans. Multi-line comments (/* */) cannot be nested within each other and attempting to do so may lead to compiler errors.
Example:
/*
This function calculates the factorial of a given number.
Factorial of n is defined as n! = n * (n-1) * (n-2) * ... * 1
*/
int calculateFactorial(int n) {
// ... code here ...
}
Multi line comment in C++ is used for:
The key to effective commenting lies in understanding when it's truly beneficial and when it's just code clutter. Let us learn more about properly using the C++ comment line.
Here are some situations where you should use the C++ comment line:
Here are some situations where you should not use the C++ comment line:
Here is how we can maintain clarity and conciseness in C++ comments:
In team development environments, C++ comments become a vital communication tool:
Here are some tips for team commenting:
Looking for how to comment in C++ shortcut? Here are the shortcuts for C++ comments:
I want to mention that some code editors (like Visual Studio) might have slightly different shortcuts or additional options for commenting. We should always check our editor's documentation if unsure. Also, many editors allow us to customize keyboard shortcuts to our preference.
Let us discuss some advanced commenting techniques that go beyond basic comments.
When you encounter a bug, use comments to disable sections of your code one by one. This helps narrow down where the issue lies. Comment out code blocks to test alternative implementations or temporarily disable features to see how it affects the overall program.
Example:
//calculateDiscount(price, age); // Original code
price = price * 0.9; // Bypass the calculation temporarily for testing
Preprocessor directives (#ifdef, #ifndef, #else, #endif) allow you to include or exclude code blocks based on conditions defined during compilation. Comments can also be used in conjunction to explain the reasoning behind conditional sections.
Example:
#ifdef DEBUG // If the 'DEBUG' symbol is defined during compilation
// cout << "Debugging information: " << var << endl; // Print debug output
#endif
Doxygen is a popular tool that can parse specially formatted comments within your code to automatically generate clear and organized documentation. Doxygen-style comments use specific tags (e.g., @brief, @param, @return) to describe functions, parameters, and more. While Doxygen leverages comments, it's a powerful tool that creates professional-level documentation for your projects.
Here is an example of C++ comments:
#include <iostream>
int main() {
int numApples = 10; // Number of apples in the basket
int numOranges = 5; // Number of oranges in the basket
int totalFruits = numApples + numOranges;
std::cout << "Total number of fruits: " << totalFruits << std::endl;
return 0;
}
If you wish to learn how to code in C++, you can check out upGrad’s software engineering courses.
Let us discuss a few solid commenting habits.
Example:
int x = 5; // Assign the value 5 to the variable x
Why it's bad: This comment merely restates what the code itself does.
Example:
int maxAttempts = 3; // Maximum number of login retries before lockout
Why it's good: Clarifies the purpose behind the value choice.
Example:
// This function calculates the area of a rectangle by taking
// the length and the width as inputs, multiplying them together,
// and then returning the result of the multiplication.
double calculateArea(double length, double width) {
// ...
}
Why it's bad: The comment is long and adds little value beyond what the code itself and function name convey.
Example:
// Assumes length and width are non-negative values.
double calculateArea(double length, double width) {
// ...
}
Why it's good: Provides a crucial assumption about the function's inputs
Here is a task for you. Check the code below and add comments to explain the logic behind the discount calculation. Also, consider where additional clarifications might be helpful.
double calculateDiscount(double originalPrice, int customerAge, bool isMember) {
double discount = 0.0;
if (customerAge > 65) {
discount = 0.15; // Senior discount
}
if (isMember) {
discount += 0.05; // Member discount
}
if (originalPrice > 50 && discount == 0) {
discount = 0.02; // Courtesy discount for larger purchases
}
return originalPrice * (1 - discount);
}
While it might seem like an additional step during the coding process, investing time in writing clear and purposeful comments pays incredible dividends in the long run. Comments capture our thought processes and decisions, preventing them from being lost as time passes or as teams change. Modifying or expanding well-commented code becomes significantly less daunting, reducing the risk of introducing new bugs.
Remember, commenting isn't just about explaining what your code does, it is about illuminating the why behind it. By embracing effective commenting practices, we create code that is both functional and sustainable, benefiting not only our current project but also any future endeavors it may become a part of.
If you wish to learn programming languages such as C++, you can check out upGrad’s computer science programs such as the Master’s in Computer Science Program.
What are comments in C++?
Comments in C++ are lines of text that the compiler ignores, allowing you to add notes and explanations within your code.
How many types of comments are there in C++?
There are two types of comments in C++: single-line comments (//) and multi-line comments (/* */).
What is the purpose of comments in C++?
Comments in C++ are used to explain code, improve readability, and make it easier to understand and maintain, especially for yourself and other developers.
Why are comments used in C++?
Comments are used in C++ to:
Can comments be nested in C++?
No, comments cannot be nested within each other in C++.
How do you write comments in C++?
How do you comment in C++ shortcut?
Common shortcuts for commenting:
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.