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

后端 未结 9 1469
眼角桃花
眼角桃花 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题