Search code examples
cc89variable-declaration

Are there any drawbacks when I declare variables inside an IF body?


I have that functionality inside a function that is encapsulated within an #ifdef block that has an if() statement attached to it:

int myfunction(void) {
  int condition = 0;
#ifdef USE_WHATEVER
  int othervar  = 0;
#endif /* USE_WHATEVER */
  /* some code */
#ifdef USE_WHATEVER
  if( condition ) {
    othervar++;
    /* do other things with othervar */
  }
#endif /* USE_WHATEVER */

The variable othervar is only used inside the #ifdef block. Since the whole #ifdef block is an if statement, I could pull the declaration of othervar inside the if block:

int myfunction(void) {
  int condition = 0;
  /* some code */
#ifdef USE_WHATEVER
  if( condition ) {
    int othervar = 0;
    othervar++;
    /* do other things with othervar */
  }
#endif /* USE_WHATEVER */

This seems much cleaner to me than the first example. However, are there any drawbacks (performance, ...) of doing such?


Solution

  • In c89, variables can only be declared at the beginning of a block. Some ppl/coding standards would put all variable declarations at the top of the function, like you are seeing here. However, variables may be declared at the beginning of any block.

    You need to consider the scope of othervar. If it is used only inside the if block then it is safe to move the declaration to the beginning of the if block.

    There should not be any performance drawback. The compiler is not unlikely to generate the exact same code for the two cases.