Home > Uncategorized > Handy Comment Block

Handy Comment Block

Quite a while ago, I found a really useful way to use C-style comment blocks to quickly enable and disable pieces of code.

Let’s say I have a loop that I want to toggle on and off for testing purposes.

for ( int i=0; i < 100; ++i ) {
  do_something_cool( i, 2*i );
}

There are two ways (and I’ll show you a third) to comment this code.  Both of which you already know.  This

/*for ( int i=0; i < 100; ++i ) {
  do_something_cool( i, 2*i );
} */

and this

//for ( int i=0; i < 100; ++i ) {
//  do_something_cool( i, 2*i );
//}

Not very exciting.  What's more, with long comment blocks, the former can be cumbersome, and the latter... well... O(n) isn't fantastic time-efficiency when you're typing two slashes on every single line of code.  The new method is just as quick to implement as a C-style comment, but far easier to toggle:

//*
for ( int i=0; i < 100; ++i ) {
  do_something_cool( i, 2*i );
} //*/

Just remove the very first slash will turn the comment block "on":

/*
for ( int i=0; i < 100; ++i ) {
  do_something_cool( i, 2*i );
} //*/

Re-insertiing the slash will disable the comment (turn it "off') again. Of course, loads of editors and IDEs have a button to comment/uncomment code with the click of a button once it's highlighted, but for quick toggling, I've found this method even faster. Enjoy.

  1. Josiah
    August 7th, 2009 at 13:56 | #1

    Most code editors support automatic comment blocking on a selection. Emacs has M-;, Eclipse has C-/, etc.

  1. No trackbacks yet.