Usually it's as simple as using your editor to select a region then instructing it to comment out that region.
If using C-style comments – by which I mean comments delimited by /*
and */
– then bear in mind they do not nest, so you may run into problems with real
comments in the code you want to comment out, or even with commenting-out code
which has already been commented-out.
I came to C++ from a C background, and remember attending a training course at which the presenter pointed out how easy it was to comment out C++ comments using C comments:
/*
for (Surfaces::iterator sf = surfaces.begin();
sf != surfaces.end();
++sf) {
// std::cout << "Drawing: " << *sf << "\n";
sf->draw();
}
*/
Oh dear!
If your editor's syntax highlighting makes it obvious that the whole loop is commented out, great. Would it still be obvious if, for example, you were viewing the source file on a remote computer via a telnet session? Or if you were code-reviewing a printed version of the file? Or if you had hit a commented-out line while searching? Or even if you were at a customer site and didn't have access to your favourite editor?
The more useful thing to say about C++ comments is that they run from where they start until the end of the line, and therefore do not suffer from this nesting problem. So a C++ comment can be commented out by a C++ comment!
// for (Surfaces::iterator sf = surfaces.begin();
// sf != surfaces.end();
// ++sf) {
// // std::cout << "Drawing: " << *sf << "\n";
// sf->draw();
// }
If using C-style comments, then the following style makes it clear which lines are part of the comment:
/* for (Surfaces::iterator sf = surfaces.begin();
* sf != surfaces.end();
* ++sf) {
* // std::cout << "Drawing: " << *sf << "\n";
* sf->draw();
* }
*/
If your editor does not allow you to easily comment out a lengthy region of code in this way then either use a better editor or read the rest of this article and consdier whether commenting out the code is really what's required.
A more heavy duty way to stop a block of code from executing is to instruct the preprocessor to skip past it.
#if 0
for (Surfaces::iterator sf = surfaces.begin();
sf != surfaces.end();
++sf) {
// std::cout << "Drawing: " << *sf << "\n";
sf->draw();
}
#endif
If this technique is used, the preprocessed-out code blends perfectly with the executable code. Even syntax-highlighting does not expose the fact that the code will not be executed.
Copyright © 2004 Thomas Guest |