I was reading the answer to another SO question regarding the declaration of variables inside for
loops. The accepted answer brings this very useful code sample, which I extend slightly by adding an extra for loop externally:
for (int j=0; j<N; j++)
{
int i, retainValue;
for (i=0; i<N; i++)
{
int tmpValue;
/* tmpValue is uninitialized */
/* retainValue still has its previous value from previous loop */
/* Do some stuff here */
}
/* Here, retainValue is still valid; tmpValue no longer */
}
As thigs are, tmpValue
is meant to be used only inside the inner for
, and its existance would cease at the end of the inner loop's life. However, because the loop is cascaded within another one, and assuming I'd actually like tmpValue
to retain its value throughout the whole external loop execution, would it be good practice to assign the static
keyword to tmpValue
?
for (int j=0; j<N; j++)
{
int i, retainValue;
for (i=0; i<N; i++)
{
static int tmpValue;
/* tmpValue is uninitialized */
/* retainValue still has its previous value from previous loop */
/* Do some stuff here */
}
/* Here, retainValue is still valid; tmpValue no longer */
}
The reason I ask is that some arguments in favour of tmpValue
to be defined inside the inner loop had to do with readability and optimality of code. I am not sure neither are still true with my second example.