Search code examples
cif-statementstackembeddedmisra

Is declaring a variable inside an if statement in c a bad habit?


My assumption is that this is going to mess with checkers and stack analysis. I can't prove my assumption and I don't think C99 will complain. Probably neither c89 will because the definition is immediately after the opening of the curly brace:

 if(true == condition){
       int i = 0; 
       /* do stuff with i */
 }else{ 
   foo():
 }

The two paths will lead to different stack usage. Declaring i outside the if/else statement will lead to a more defined stack usage (ok, I am branching to foo,so the stack will not be exactly the same in the two cases). But Misra advises to limit the scope of a variable closest to its usage.

Am I overthinking it or could there be a rationale in my assumption?


Solution

  • The code is fine in any version of C (except C90 does not support true).

    The two paths will lead to different stack usage.

    This is mostly a myth. Modern compilers stack a variable if they can determine that it is needed, regardless of where you place the declaration.

    If the variable is allocated in a register, then it will only be allocated when the program takes the path where your example declares the variable. This is not because of where the declaration is placed, but because that path will be executed. So again, for the sake of performance, it doesn't matter where the variable is declared, as long as it is somewhere in local scope and not at file scope.

    It is good practice to limit the scope of variables as much as possible. But this is to avoid unintentional bugs and namespace collisions.

    But Misra advises to limit the scope of a variable closest to its usage.

    No it doesn't, but some static analysers require you to do that, on top of the MISRA requirement. Both MISRA-C:2004 8.7 and MISRA-C:2012 8.9 only require that you place a variable at block scope, if it is only used by one function. That's it.

    MISRA does however say:

    Within a function, whether objects are defined at the outermost or innermost block is largely a matter of style