Good question!
I tried to answer the first question using the following source code:
1 2 3 4 5 6 7 8 9 10 11 12
|
static int a;
int fTest();
int main() {
int b;
a=a+11;
b=b+22;
}
int fTest(){
int c;
c=c+33;
}
|
gcc with option -S give us the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
.file "variabili.c"
.def ___main; .scl 2; .type 32; .endef
.text
.globl _main
.def _main; .scl 2; .type 32; .endef
_main:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
andl $-16, %esp
movl $0, %eax
addl $15, %eax
addl $15, %eax
shrl $4, %eax
sall $4, %eax
movl %eax, -8(%ebp)
movl -8(%ebp), %eax
call __alloca
call ___main
addl $11, _a
leal -4(%ebp), %eax
addl $22, (%eax)
leave
ret
.globl _fTest
.def _fTest; .scl 2; .type 32; .endef
_fTest:
pushl %ebp
movl %esp, %ebp
subl $4, %esp
leal -4(%ebp), %eax
addl $33, (%eax)
leave
ret
.lcomm _a,16
|
Note that I used the int constant 11, 22 and 33 to identify easily the fragment of assembler code of interest.
We can observe that:
1) For what concern the global variable
b and the local variable
c, they are both popped from the stack and then the addition is performed;
2) For what concern the static int variable
a the compiler use the addl instruction with the absolute address of the space reserved to the variable a with the
.lcomm _a,16 assembly directive.
My friends it seems that static variable perform better than global and local variables.
For what concern the second question, I wrote the following code:
1 2 3
|
int main() {
int a=1+3;
}
|
And, again, gcc with -S option give us:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
.file "ottimo.c"
.def ___main; .scl 2; .type 32; .endef
.text
.globl _main
.def _main; .scl 2; .type 32; .endef
_main:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
andl $-16, %esp
movl $0, %eax
addl $15, %eax
addl $15, %eax
shrl $4, %eax
sall $4, %eax
movl %eax, -8(%ebp)
movl -8(%ebp), %eax
call __alloca
call ___main
movl $4, -4(%ebp)
leave
ret
|
As we can see, the compiler, even without teh selection of optimization options, optimize the code and translate
a= 1+3 as
movl $4, -4(%ebp), that is
a =4.
Q.E.D. :)