"ok"posted the following on 2006-03-10:
I have the following code:
void foo(void)
{
const int array[100] = ....;
// do stuff with array
}
I mostly use code like this so my program doesnt waste memory because array
only gets allocated when foo is called.
But now I heard from somebody that the following code is the same in terms
of memory footprint:
static int array[100] = .....
void foo(void)
{
// do stuff with array
}
is that true?
Memory footprint aside, its certainly not in terms of modularised
programming
However, firing up gdb and stepping into foo() gave me code like this
for an array of "const int array[3]={255,2,3}"
Dump of assembler code for function foo:
0x08048378 <foo+0>: push %ebp
0x08048379 <foo+1>: mov %esp,%ebp
0x0804837b <foo+3>: sub $0x10,%esp
0x0804837e <foo+6>: mov 0x80484cc,%eax
0x08048383 <foo+11>: mov %eax,0xfffffffc(%ebp)
0x08048386 <foo+14>: leave
0x08048387 <foo+15>: ret
End of assembler dump.
As you can see, there is no "function time" reinitialising and
creation of your array. If you want to generate an assembler file then
you will probably see your array as a global data object.
Now change the initiliasation of your array to include a run time
variable in foo and you will see the array re-initialised each
function call e.g
int i=255;
const int array[3]={1,i,3]; //const initialisation is fine
Stepping in with instructions displayed gives:
Dump of assembler code for function foo:
0x08048378 <foo+0>: push %ebp
0x08048379 <foo+1>: mov %esp,%ebp
0x0804837b <foo+3>: sub $0x28,%esp
0x0804837e <foo+6>: movl $0xff,0xfffffff8(%ebp)
0x08048385 <foo+13>: movl $0x1,0xffffffec(%ebp)
0x0804838c <foo+20>: mov 0xfffffff8(%ebp),%eax
0x0804838f <foo+23>: mov %eax,0xfffffff0(%ebp)
0x08048392 <foo+26>: movl $0x3,0xfffffff4(%ebp)
0x08048399 <foo+33>: mov 0xffffffec(%ebp),%eax
0x0804839c <foo+36>: mov %eax,0xfffffffc(%ebp)
0x0804839f <foo+39>: sub $0x8,%esp
0x080483a2 <foo+42>: pushl 0xfffffffc(%ebp)
0x080483a5 <foo+45>: push $0x80484ec
0x080483aa <foo+50>: call 0x80482b0 <_init+56>
0x080483af <foo+55>: add $0x10,%esp
0x080483b2 <foo+58>: mov 0xfffffffc(%ebp),%eax
0x080483b5 <foo+61>: leave
0x080483b6 <foo+62>: ret
End of assembler dump.
Of course, Gcc specific, but it can be fun to see how C is compiled
into native code : and often no real need to generate seperate
assembler files.