Comments
Programs are read not only by computers, but also by people: by your classmates, your colleagues, and by you yourself a few weeks later, when you no longer remember why you wrote something the way you did. That's why programming languages have comments: notes in the code that the compiler ignores.
In C++, a comment starts with two slashes //. Everything after them, up to the end of the line, is ignored. A comment can be on a line of its own, or at the end of a line with code:
// Prints the price of two cinema tickets
std::cout << 12 + 12 << std::endl; // one ticket costs 12 dollarsThis prints only:
24You can write a longer note between /* and */. Such a comment can even span several lines:
/*
Author: Anna Smith
The program prints today's to-do list.
*/A good comment says what you can't see in the code at first sight: what a part of the program is for, or why it is written the way it is.
Comments are also useful for switching code off for a while without deleting it. Programmers call this commenting out: put // at the start of a line, and the line no longer runs. When you want it back, just delete the //.
std::cout << "This line runs." << std::endl;
// std::cout << "This one doesn't." << std::endl;This prints:
This line runs.Instructions
- 1
At the start of the program, above the
#includeline, add a comment that says what the program does, for example// My to-do list. - 2
You've already taken out the trash. Comment out the line that prints
take out the trash, so that the program prints only:Today's tasks: do my math homework call grandma