Is if(TRUE) a good idea in C?

后端 未结 17 3457
忘了有多久
忘了有多久 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:35

    You probably want to create a new function for that scope.
    If it truly needs to have it's own scope, it's probably a separate logical function anyway.

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

    You can remove the

    if(TRUE)
    

    and just leave the braces, which by themselves define a new syntactic block - a compound statement.

    This is definitely cleaner than the false if you had before, but you might still like to ask yourself why you want to create a new block - would it be better to define a subroutine?

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

    As far as I know you can create a scope without if.

    Use just the braces like this:

    {
        int x;
    
    }
    

    And I recommend against

    if (TRUE)
    

    since it hinders readibility.

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

    As so many answers already said, you don't need the "if" stuff. Just create the bare block. But i want to get at another point. In C, you can create variable declarations anywhere in a block, not only at the start. In C89, you had that restriction. Starting with C99 (that's 10 years now), you don't have that restriction anymore, although some compilers will moan anyway. GCC won't, though, if you tell it to use the most "recent" C Standard with the -std=c99 option.

    Because there are still compilers in existence that moan by default, i would not prefer mixing declarations and code though. I would keep putting declarations at the start of blocks for compatibility reasons.

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

    First of all, a new block doesn't need to be an if block. It could simply be a section of code surrounded by braces, like this:

    void foo() {
     ... Do some stuff ...
    
     {
         char a;
         int b;
    
         ... Do some more stuff ...
     }
    
     ... Do even more stuff ...
    }
    

    Second of all, in any modern C compiler which complies to the C standard (I think C99), you can declare variables anywhere in the block, so you don't need to create a new block at all.

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

    Assuming that you use an old compiler (like I do, it's for old hardware), that you skip the if(TRUE) like others have suggested, and that you have a really HUGE function (witch you should not have in the first place), then I think it's sort of ok. I have done it but it did not feel good...

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