What exactly does an #if 0 … #endif block do?

后端 未结 9 1430
眼角桃花
眼角桃花 2020-12-02 04:38

In C/C++

What happens to code placed between an #if 0/#endif block?

#if 0

//Code goes here

#endif


        
相关标签:
9条回答
  • 2020-12-02 05:23

    Not quite

    int main(void)
    {
       #if 0
         the apostrophe ' causes a warning
       #endif
       return 0;
    }
    

    It shows "t.c:4:19: warning: missing terminating ' character" with gcc 4.2.4

    0 讨论(0)
  • 2020-12-02 05:24

    It is a cheap way to comment out, but I suspect that it could have debugging potential. For example, let's suppose you have a build that output values to a file. You might not want that in a final version so you can use the #if 0... #endif.

    Also, I suspect a better way of doing it for debug purpose would be to do:

    #ifdef DEBUG
    // output to file
    #endif
    

    You can do something like that and it might make more sense and all you have to do is define DEBUG to see the results.

    0 讨论(0)
  • 2020-12-02 05:25

    It's identical to commenting out the block, except with one important difference: Nesting is not a problem. Consider this code:

    foo();
    bar(x, y); /* x must not be NULL */
    baz();
    

    If I want to comment it out, I might try:

    /*
    foo();
    bar(x, y); /* x must not be NULL */
    baz();
    */
    

    Bzzt. Syntax error! Why? Because block comments do not nest, and so (as you can see from SO's syntax highlighting) the */ after the word "NULL" terminates the comment, making the baz call not commented out, and the */ after baz a syntax error. On the other hand:

    #if 0
    foo();
    bar(x, y); /* x must not be NULL */
    baz();
    #endif
    

    Works to comment out the entire thing. And the #if 0s will nest with each other, like so:

    #if 0
    pre_foo();
    #if 0
    foo();
    bar(x, y); /* x must not be NULL */
    baz();
    #endif
    quux();
    #endif
    

    Although of course this can get a bit confusing and become a maintenance headache if not commented properly.

    0 讨论(0)
提交回复
热议问题