I tried the two following pieces of code:
void swap_woPointer()
{
int a=5;
static int b=5;
printf("value of a : %d , value of b: %d \n", a, b);
printf("address of a: %p , address of b %p \n", &a, &b);
a++;
b++;
}
void main(int argc, char *argv[])
{
int ii;
for (ii=0; ii<10; ii++){
swap_woPointer();
}
}
and
void swap_woPointer()
{
int a;
static int b;
printf("value of a : %d , value of b: %d \n", a, b);
printf("address of a: %p , address of b %p \n", &a, &b);
a++;
b++;
}
void main(int argc, char *argv[])
{
int ii;
for (ii=0; ii<10; ii++){
swap_woPointer();
}
}
The only difference between the two pieces of code is that once I only declared the variables a and b
int a;
static int b;
and in the other case I defined them
int a=5;
static int b=5;
The output that I obtain is different for the two cases. In the case in which I only declared the variables, I obtain
value of a : 0 , value of b: 0
address of a: 0xffffcbbc , address of b 0x100407000
value of a : 1 , value of b: 1
address of a: 0xffffcbbc , address of b 0x100407000
value of a : 2 , value of b: 2
address of a: 0xffffcbbc , address of b 0x100407000
value of a : 3 , value of b: 3
address of a: 0xffffcbbc , address of b 0x100407000
value of a : 4 , value of b: 4
address of a: 0xffffcbbc , address of b 0x100407000
value of a : 5 , value of b: 5
address of a: 0xffffcbbc , address of b 0x100407000
value of a : 6 , value of b: 6
address of a: 0xffffcbbc , address of b 0x100407000
value of a : 7 , value of b: 7
address of a: 0xffffcbbc , address of b 0x100407000
value of a : 8 , value of b: 8
address of a: 0xffffcbbc , address of b 0x100407000
value of a : 9 , value of b: 9
address of a: 0xffffcbbc , address of b 0x100407000
whereas if I define the variables rightaway, I obtain
value of a : 5 , value of b: 5
address of a: 0xffffcbbc , address of b 0x100402010
value of a : 5 , value of b: 6
address of a: 0xffffcbbc , address of b 0x100402010
value of a : 5 , value of b: 7
address of a: 0xffffcbbc , address of b 0x100402010
value of a : 5 , value of b: 8
address of a: 0xffffcbbc , address of b 0x100402010
value of a : 5 , value of b: 9
address of a: 0xffffcbbc , address of b 0x100402010
value of a : 5 , value of b: 10
address of a: 0xffffcbbc , address of b 0x100402010
value of a : 5 , value of b: 11
address of a: 0xffffcbbc , address of b 0x100402010
value of a : 5 , value of b: 12
address of a: 0xffffcbbc , address of b 0x100402010
value of a : 5 , value of b: 13
address of a: 0xffffcbbc , address of b 0x100402010
value of a : 5 , value of b: 14
address of a: 0xffffcbbc , address of b 0x100402010
I do not understand where the difference comes from. It somehow has to be related to the memory allocation. I thought that in both cases I should obtain the same result, e.g. the variable a, which is declared not to be static, should be allocated once every time the function is called. Apparently this is only the case when the variable is directly defined and not merely declared.