--- Lun 7/12/09, johnmatthews2000 <[email protected]> ha scritto:
> Da: johnmatthews2000 <[email protected]>
> Oggetto: [c-prog] Re: const modifier and explicit cast from const int to > int
> A: [email protected]
> Data: Lunedì 7 dicembre 2009, 11:07
>
>
> Probably my understanding of 'easiest' is incorrect, in which case I
> would like to know what it is the code is actually doing. If I
> understood x86 assembler I would try generating it.
I did it. The GCC compiler behaves exactly as Gerardo wrote:
> See there's nothing wrong with ri2 getting another value: it's not
> itself const; were ri2 const int& ri2 = (int&) i2, then the
> assignment ri2 = 102 would be impossible.
>
> So, 102 affects ri2 only, but not i2, const.
.
The following is the output of the 'assemble-only' flag of GCC, I added the
comment lines for clarity:
// const int i2 = 2; stores the immediate value 2 in 'i2'
// 12 bytes below EBP
movl $2, -12(%ebp)
// int& ri2 = (int&) i2;
// in order to implement references,the GCC compiler gets the address
// of 'i2' and stores it in 'ri2'
// note that 'ri2' is _not_ a variable at the same address as 'i2': it is
// stored in a different location: -8(%ebp)
leal -12(%ebp), %eax
movl %eax, -8(%ebp)
// ri2 = 102; store immediate value 102 in 'ri2'
// the compiler stores the immediate value at the address pointed to by EAX
// which is loaded with the address stored in 'ri2'
// in fact, the const variable 'i2' _is_ modified
movl -8(%ebp), %eax
movl $102, (%eax)
// printf("%d\n", ri2);
// the address contained in 'ri2' is loaded in EAX
// so EAX points to 'i2' which contains the value 102
movl -8(%ebp), %eax
movl (%eax), %eax
// the content of 'i2' is pushed on the stack as second parameter
// of printf() we get 102
// as output because 'i2' is actually 102
movl %eax, 4(%esp)
movl $.LC0, (%esp)
call printf
// printf("%d\n", i2)
// this is the most interesting part
// when we have to printf() 'i2', the compiler does not push
// the content of the memory area 'i2' on the stack
// Instead, an immediate operand
// of value 2 is pushed on the stack as the second parameter to printf()
// thus obtaining the 'const' behaviour
movl $2, 4(%esp)
movl $.LC0, (%esp)
call printf
Regards
Luciano