Is declaration of variables expensive?

前端 未结 12 1151
长情又很酷
长情又很酷 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

    In C99 and later (or with the common conforming extension to C89), you are free to mix statements and declarations.

    Just as in earlier versions (only more so as compilers got smarter and more aggressive), the compiler decides how to allocate registers and stack, or do any number of other optimizations conforming to the as-if-rule.
    That means performance-wise, there's no expectation of any difference.

    Anyway, that was not the reason such was allowed:

    It was for restricting scope, and thus reducing the context a human must keep in mind when interpreting and verifying your code.

提交回复
热议问题