How is conditional initialization handled and is it a good practice?

后端 未结 5 547
情歌与酒
情歌与酒 2020-12-06 18:46

I am trying to decide between several possible practices. Say, my function has a number of if() blocks, that work on data, that is unique to them.

  • Should I

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 19:02

    Should I declare and initialize the local (for the block) data inside the block?

    Absolutely: this tends to make programs more readable.

    Does this have runtime performance cost (due to runtime allocation in the stack)?

    No: all allocations are done upfront - the space on the stack is reserved for variables in all branches upon entering a function, not when the branch is entered. Moreover, this could even save you some space, because the space allocated for variables in non-overlapping branches can be reused by the compiler.

    Or should I declare and/or initialize all variables at function entry, so that is is done in one, possibly faster, operation block?

    No, this is not faster, and could be slightly more wasteful.

    Or should I seperate the if() blocks in different functions, even though they are only a couple of lines long and used only one in the program?

    That would probably have a negative impact on readability of your program.

提交回复
热议问题