Search code examples
cc99

Is there any benefit from declaring variables at the beginning of a function?


I know that pre C99 compilers needed variables to be declared at the beginning of a function to calculate stack size. Then the requirement was lifted. Nowadays, besides backwards compability, is there any benefit from still sticking to that scheme, or maybe is declaring variables only when they are needed and where they are needed better? (for instance in an if statement, where one branch requires a variable but second one doesn't)


Solution

  • The answer is no. There is no compilation or other computing benefit from declaring identifiers at the beginning of a function.

    Good modern compilers analyze where values are used in code, so the locations of declarations are irrelevant as long as they do not affect semantics (such as moving a declaration into a compound statement, reducing its scope).

    In some cases, there may be benefit from telling a human reader what you are going to do at the beginning of a function or block. Generally, it is beneficial to declare identifiers just where they are needed, as this tends to reduce the number of things a reader has to think about at one time. However, if there is some pattern or rhyme and reason to the algorithm a function is going to perform, then showing some aspects of that at the beginning can help the reader comprehend it.