While coding in C, I came across the below situation.
int function ()
{
if (!somecondition) return false;
internalStructure *str1;
internalStructure *str
If you have this
int function ()
{
{
sometype foo;
bool somecondition;
/* do something with foo and compute somecondition */
if (!somecondition) return false;
}
internalStructure *str1;
internalStructure *str2;
char *dataPointer;
float xyz;
/* do something here with the above local variables */
}
then the stack space reserved for foo
and somecondition
can be obviously reused for str1
etc., so by declaring after the if
, you may save stack space. Depending on the optimization capabilities of the compiler, the saving of stack space may also take place if you flatten the fucntion by removing the inner pair of braces or if you do declare str1
etc. before the if
; however, this requires the compiler/optimizer to notice that the scopes do not "really" overlap. By positining the declarations after the if
you facilitate this behaviour even without optimization - not to mention the improved code readability.