-1

Does re-declaring the same variable over and over again affect the performance of the code?

int i,a;
for(i=0;i<10;i++)
{
// Some operations with a
}

V/S

int i;
for(i=0;i<10;i++)
{
int a;
// Some operations with a
}

1 Answers1

2

Normally "stack variables", what are really local variables, are zero-cost. The only price you'd pay is if there's initialization of some sort.

The compiler may or may not reserve memory for that value. In the second case you don't actually use a so it will probably be eliminated by the optimization pass, making it truly zero cost.

Don't think of them in terms of "stack". That's an antiquated concept that pre-dates optimizing compilers.

tadman
  • 208,517
  • 23
  • 234
  • 262