Is declaration of variables expensive?

前端 未结 12 965
长情又很酷
长情又很酷 2021-02-01 00:39

While coding in C, I came across the below situation.

int function ()
{
  if (!somecondition) return false;

  internalStructure  *str1;
  internalStructure *str         


        
12条回答
  •  执笔经年
    2021-02-01 00:49

    If you have this

    int function ()
    {
       {
           sometype foo;
           bool somecondition;
           /* do something with foo and compute somecondition */
           if (!somecondition) return false;
       }
       internalStructure  *str1;
       internalStructure *str2;
       char *dataPointer;
       float xyz;
    
       /* do something here with the above local variables */    
    }
    

    then the stack space reserved for foo and somecondition can be obviously reused for str1etc., so by declaring after the if, you may save stack space. Depending on the optimization capabilities of the compiler, the saving of stack space may also take place if you flatten the fucntion by removing the inner pair of braces or if you do declare str1 etc. before the if; however, this requires the compiler/optimizer to notice that the scopes do not "really" overlap. By positining the declarations after the if you facilitate this behaviour even without optimization - not to mention the improved code readability.

提交回复
热议问题