mardi 18 décembre 2018

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?

Aucun commentaire:

Enregistrer un commentaire