This is a very small program which I wrote last night:
void testWithFunction(int val) {
int someA;
printf ("SomeA: %x %d \n ", &someA, someA);
someA = val;
}
int main() {
int j = 5;
while ( j-- ) {
int i;
if ( j == 4) { i = 10; }
printf("i: %x %d \n", &i, i);
}
testWithFunction(5);
testWithFunction(10);
testWithFunction(0);
// system("pause");
return 0;
}
The output to the above was:
i: 28ff20 10
i: 28ff20 10
i: 28ff20 10
i: 28ff20 10
i: 28ff20 10
SomeA: fffffffe 2686916
SomeA: 5 2686916
SomeA: a 2686916
I used to think that variables declared inside loops had local scope - they were destroyed when the loop terminate. For each new iteration, all its local variables would be created again. However with this example, it seems that the same variable is reused each time and so, the variable can even remember its last written value. The same applies for functions - Variables local to a function should be destroyed when the function terminates and should be re-created when the function is called again! However, the results suggest that the variables behave as if they are declared with the static keyword! This is something new to me. Please correct me - Is the static keyword implicit for all variables??
I have tried the same thing with structure type nodes and found the same result. So I dont think we should assume that the variables are re-allocated to the same memory space and hence they retain their value. ( I agree "destroy" doesnt actually deletes the old value)
Example 2:
#include <stdio.h>
typedef struct node
{
int val;
struct node *next;
}node;
int main()
{
int i;
node newtemp,root,temp;
scanf("%d",&i);
while(i--)
{
node array[i];
node n;
int j;
for(j = 0; j < i; j++) {
printf (" array: %x ", &array[j] );
}
n.val = i;
n.next = NULL;
printf("node: %x\n", &n);
}
return 0;
}
Output:
4
array: 28feb0 array: 28feb8 array: 28fec0 node: 28ff00
array: 28fec0 array: 28fec8 node: 28ff00
array: 28fec0 node: 28ff00
node: 28ff00