cpp / beginner
Snippet
Code Comments for Clarity
Comments are annotations in code that are ignored by the compiler but help programmers understand the logic. Single-line comments use // and comment everything after on that line. Multi-line comments use /* to start and */ to end, allowing text across multiple lines. Well-placed comments explain why code does something, not what it does - the code itself should be self-explanatory for the what.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>using namespace std;// Global constant for maximum scoreconst int MAX_SCORE = 100;/* Multi-line comment:This program calculates a student's average gradefrom three test scores and displays the result.It uses the global MAX_SCORE constant for validation.*/int main() {// Initialize three test scoresint score1 = 85;int score2 = 90;int score3 = 78;// Calculate average using integer divisionint average = (score1 + score2 + score3) / 3;// Display resultscout << "Test scores: " << score1 << ", " << score2 << ", " << score3 << endl;cout << "Average: " << average << endl;// Validate against maximumif (average > MAX_SCORE) { // Should never happencout << "Error: Average exceeds maximum!" << endl;}return 0; // Exit program successfully}
Breakdown
1
// Global constant for maximum score
Single-line comment explaining the purpose of the following constant declaration
2
/* Multi-line comment: ... */
Block comment spanning multiple lines for detailed program documentation
3
// Initialize three test scores
Comment describing the initialization of variables at the start of main
4
// Should never happen
Comment in line with code explaining why a condition should never trigger