Comments, Style & Program Structure
Comments
// single-line comment
/* multi-line
comment */
Comments are removed by the preprocessor — they never slow down your program.
What to comment
- ✅ Why something is done, not what (the code shows what)
- ✅ Assumptions, units ("amount in paisa"), tricky logic
- ❌ Obvious things:
i++; // increment i - ❌ Commented-out dead code (version control remembers it)
Typical structure of a C++ file
// 1. Includes
#include <iostream>
#include <string>
// 2. Constants and type definitions
constexpr double TAX_RATE = 0.13;
// 3. Function declarations / definitions
double add_tax(double amount);
// 4. main
int main() { ... }
// 5. Function definitions
double add_tax(double amount) { return amount * (1 + TAX_RATE); }
Naming conventions (pick one and be consistent)
| Thing | Common styles |
|---|---|
| Variables, functions | total_amount (snake_case) or totalAmount (camelCase) |
| Classes, types | BankAccount (PascalCase) |
| Constants | MAX_SIZE or kMaxSize |
| Private members | balance_ or m_balance |
Formatting tips
- Indent with 4 spaces (or 2) consistently
- One statement per line
- Use blank lines to separate ideas
- Use a formatter: clang-format does it automatically
Identifier rules
- Letters, digits,
_; cannot start with a digit - Case-sensitive:
total≠Total - Cannot be a keyword (
int,class,return…) - Avoid names starting with
_+ capital letter or__(reserved)
Example
// expense_summary.cpp — prints a small monthly summary
#include <iostream>
// Constants
constexpr double VAT_RATE = 0.13; // Nepal VAT: 13%
// Function declaration (definition is below main)
double with_vat(double amount);
int main() {
double groceries = 2500.0; // amounts in rupees
double internet = 1500.0;
/* VAT applies to internet bills only
in this simplified example. */
double total = groceries + with_vat(internet);
std::cout << "Groceries: Rs. " << groceries << '\n';
std::cout << "Internet (with VAT): Rs. " << with_vat(internet) << '\n';
std::cout << "Total: Rs. " << total << '\n';
return 0;
}
// Adds VAT to an amount
double with_vat(double amount) {
return amount * (1 + VAT_RATE);
}
/* Output:
Groceries: Rs. 2500
Internet (with VAT): Rs. 1695
Total: Rs. 4195
*/