Saturday, February 19, 2011

Commenting out comments

I've noticed, using visual studio 2003, that I can "comment out" my comments to make them no longer be comments. This one needs an example:

If I have:

/*
int commented_out = 0;
*/

I can comment out the /* and */ with // and code within the /* and */ is no longer "commented out" (the text changes to non-comment color and the compiler treats it as code once again). Like so:

///*
int commented_out = 0;
//*/

I've found this is true for msvc 2003, is this normal C++ behavior or is it just a fluke that works with this compiler?

From stackoverflow
  • It should work in any compiler as the // is encountered first in the input stream.

    I tend to use #if 0 for this sort of stuff and change it to #if 1 to uncomment, shown here:

    #if 0
        int commented_out = 0;
    #endif
    

    Then I don't have to worry about comment markers at all.

  • Yep, this is perfectly normal behavior. The C++ standard says that a /* is the start of a comment block only if it itself is not commented out. I often use what you've written above to comment or uncomment a block of code by adding/deleting one character. A nice little trick for switching between two blocks of code, one of which is always commented out is:

    //*
    code block 1 (uncommented)
    /*/
    code block 2 (commented)
    //*/

    Now, delete one slash from the start, and it becomes

    /*
    code block 1 (commented)
    /*/
    code block 2 (uncommented)
    //*/

    Not something to use in production code, but very useful for quick debugging changes.

    Adam Jaskiewicz : Hadn't thought of that before. That's great.
    rally25rs : cool trick! thanks!
  • Actually this works in almost any language with C style block comments.

    /*
    int foo = 0;
    /*/
    int foo = 1;
    //*/
    

    or even XML comments

    <!--->
    a
    <!-->
    b
    <!---->
    

    unfortunately I'm drawing a blank on lua's lightsaber comments

    --[[---------
    ---------]]--
    

0 comments:

Post a Comment