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

115 views Asked by At

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.

2

There are 2 answers

6
Eric Postpischil On BEST ANSWER

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

0
Vlad from Moscow On

Do not bother about memory.

The code snippets have different semantics.

In the first code snippet the (two different) variables i are visible only within if and else statements. So they can not be accessed outside the if statement.

In the second code snippet the variable i visible and alive outside the if statement. If it should be used only within the if statement then it is a bad programming style to declare a variable in a block where it is not used.