开发者

Nested Comments in C++

This should be a common problem and possibly similar to some q开发者_开发知识库uestion here but i am looking foe the best way to comment out multiple lines (rather methods ) in C++ which have comments within them .I did check out some posts on SO but couldnt get the full details on using something like if #0 .

I did check out this post Nested comments in Visual C++? but I am not on the Windows platform.


You are almost correct; essentially it is being suggested to "if-def" the section of code out. What you want to do is use the precompiler directive #if to block the code for you. Ex below shows that I want to ignore everything between the if and endif.

#if 0
/* Giant comment
 it doesn't matter what I put here */

// it will be ignored forever.
#endif

To answer your question in general though; there is not a way to have compound comments, i.e.

/* 
  /* */ <--- this closes the first /* 
*/ <--- this dangles.


The stuff between the #if 0 and #endif will be ignored by the compiler. (Your preprocessor might actually strip it out before the "compiler" can even take a look at it!)

#if 0

    /* 42 is the answer. */

    Have you tried jQuery?

    @Compiler Stop ignoring me!!

#endif

You'll have better control if you use #ifdefs:

// #define DEBUG


#ifdef DEBUG
   MyFunction();
   std::cout << "DEBUG is defined!";
#endif


// Later in your code...

#ifdef DEBUG
    std::cout << "DEBUG is still defined!";
#endif

Just uncomment the first line, and your #ifdef DEBUG code will suddenly be visible to the compiler.


P.S. This should clear any more confusion:

/*
    cout << "a";
    /*
        cout << "b";
    */
    cout << "c";
*/

The output should be "c", assuming your compiler doesn't give you any errors for the last */.


Use whatever means your editor provides to add // a the beginning of all lines.

For example in Vim you can mark the lines as a visual block and then insert at the beginning of all lines with I//. In Visual Studio you can use the CTRL-K-C shortcut to comment code blocks.


Another route assuming you are using Visual Studio is there is a handy keyboard shortcut to comment all of the currently selected code, adding // before each line. CTRL+K+CTRL+C to comment and CTRL+K+CTRL+U to uncomment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜