
A comment is text the computer IGNORES — it is only for humans. Very useful for reminding yourself what the code does.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
// This line is a note. It does nothing.
cout << "Hi" << endl; // notes can sit after code too
/* A longer note
across several lines */
return 0;
}> what you see
Hi
//LINE BY LINE
Two kinds of comment
The computer ignores comments completely. They exist only for people — including you, reading your own code tomorrow.
// Нэг мөрийн тайлбар: мөрийн төгсгөл хүртэл
/* Олон мөрийн тайлбар:
энд хэдэн ч мөр бичиж болно */
int x = 5; // мөрийн ард ч бичиж болноComments are handy for switching code off temporarily: put // in front of a line and it stops running.
White space and indentation
C++ ignores spaces and line breaks. The two programs below are identical to the computer — but not to a human.
This works, but it is painful to read:
int main(){int x=5;if(x>3){cout<<"big";}return 0;}The same program, written properly:
int main() {
int x = 5;
if (x > 3) {
cout << "big";
}
return 0;
}- Indent by 4 spaces every time you open a
{. - Leave a blank line between parts that do different things.
- Put a space around operators:
x = a + breads better thanx=a+b.
Naming things well
A good name is the best comment. int d; tells you nothing; int daysLeft; needs no explanation.
| Poor | Better |
|---|---|
int a; | int score; |
int x2; | int studentCount; |
double t; | double totalPrice; |
- A name starts with a letter or
_, never a digit. - No spaces: use
myAgeormy_age. - Case matters:
ageandAgeare two different variables.