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

c, coding-style, performance

Solution

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.

Problem

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 declare and initialize the local (for the block) data inside the block? Does this have runtime performance cost (due to runtime allocation in the stack)? Or should I declare and/or initialize all variables at function entry, so that is is done in one, possibly faster, operation block? 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? Or am I ovelooking another, cleaner, option? Is the question even answerable in it's current, general form?

Original source

Related problems