cvariablesscopeautomatic-storage

auto variables with the same name in different C blocks: memory allocation


Assume I have a structure like this in a C program:

if (res == NULL)
{
    int i = 1;
    ...
}
else
{
    int i = 2;
    ...
}

Will I save some amount of memory if I instead write

int i;

if (res == NULL)
{
    i = 1;
    ...
}
else
{
    i = 2;
    ...
}

?

The variable i is not needed outside the if-else structure.


Solution

  • No compiler of even modest quality will generate better code for either case than the other unless, possibly, its optimization features are disabled.