Nested Comments in C++

后端 未结 4 1286
南旧
南旧 2020-12-31 17:43

This should be a common problem and possibly similar to some question here but i am looking foe the best way to comment out multiple lines (rather methods ) in C++ which hav

相关标签:
4条回答
  • 2020-12-31 18:31

    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.
    
    0 讨论(0)
  • 2020-12-31 18:43

    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 */.

    0 讨论(0)
  • 2020-12-31 18:49

    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.

    0 讨论(0)
  • 2020-12-31 18:50

    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 讨论(0)
提交回复
热议问题