Is if(TRUE) a good idea in C?

后端 未结 17 3451
忘了有多久
忘了有多久 2021-02-19 01:19

In the C programming language, it is my understanding that variables can only be defined at the beginning of a code block, and the variable will have the scope of the block it w

相关标签:
17条回答
  • 2021-02-19 01:20

    Since you can just make the scope block without the if, that's a better idea.

    void foo() {
         ... Do some stuff ...
         {
             char a;
             int b;
             ... Do some more stuff ...
         }
         ... Do even more stuff ...
    }
    
    0 讨论(0)
  • 2021-02-19 01:21

    I wouldn't call myself seasoned, but I'm kind of cringing.

    My issue with it is that the if statement would lead someone to believe that something is actually being evaluated...but at runtime, the macro is either true or false there's no change of it being something else. You should either include the code or not.

    If what you mean to do is something like #ifdef DEBUG then you should do that to indicate to the reader that this is debug code...

    0 讨论(0)
  • 2021-02-19 01:24

    Just define your variables at the beginning of the block or use another function. Adding an artificial scope with empty {}s or any of the alternatives is not good practice.

    0 讨论(0)
  • 2021-02-19 01:25

    Leaving the door open for some creative folks:

    #define TRUE 0
    #define FALSE 1
    

    Just use the braces to declare the scope.

    0 讨论(0)
  • 2021-02-19 01:26

    C99 allows you to declare variables almost anywhere. However, refrain from doing it without a very good reason. Try first to split your function into smaller (possibly inline) functions.

    The only place where such a thing might make sense is when you have a variable that is initialized in the middle of your function, e.g. similar to creating an object in C++.

    0 讨论(0)
  • 2021-02-19 01:26

    Apparently I'm in the minority, but I find "just braces" much harder to read because it deviates from the usual pattern. On the (admittedly infrequent) occasions where I want a scoped block without defining another function, I prefer to include the "if", but without any macros and with a comment to explain why:

    if( 1 ) // just to establish scope
    {
       // do stuff here
    }
    
    0 讨论(0)
提交回复
热议问题