capypad
0 day streak
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
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 score
const int MAX_SCORE = 100;
 
/* Multi-line comment:
This program calculates a student's average grade
from three test scores and displays the result.
It uses the global MAX_SCORE constant for validation.
*/
 
int main() {
// Initialize three test scores
int score1 = 85;
int score2 = 90;
int score3 = 78;
// Calculate average using integer division
int average = (score1 + score2 + score3) / 3;
// Display results
cout << "Test scores: " << score1 << ", " << score2 << ", " << score3 << endl;
cout << "Average: " << average << endl;
// Validate against maximum
if (average > MAX_SCORE) { // Should never happen
cout << "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