For this code:
int main(void) {
int a = 1;
int b = 2;
int* pa = &a;
*pa = a + b;
printf("%d", a);
}
At compile time the compiler calculates how much space it needs. We have 2 integers and one pointer. So it is 2*4 + 8 = 16
. Then it specifies where the memory of a given variable is in relation to the start point address.
pa
is at the start point address and have length of 8 bytes.
b
is at start point address + 8 bytes and have length 4 bytes.
a
is at start point address + 12 bytes and have length 4 bytes.
Then go instructions for execution time:
1
at the location of a
.2
at the location of b
.a
(start point address + 12 bytes) to its absolute location and put it at location of pa
.a
and bytes at location b
, add them and then get bytes at location pa
. Use bytes at location pa
as an address and put there the calculated sum.a
converting them to decimal number first.Is this a valid translation?
Let's assume a super simple compiler is used (no optimizations). All it cares about is a valid execution of C code.
As far as I read, yes it is a valid translation. No, it is almost 100 % certainly not the translation your compiler is going to produce. The C standard has the so-called as-if rule which means the compiler is free to produce any program whose side effects are as if the program were compiled for the so-called abstract C machine and run in there.
In practice, a compiler could for example produce the following program:
'3'
into the register that is used as the first argument in function callsputchar
main
functionTo an observer, the side effects of this program would be indistinguishable from those of your program: it prints 3
and returns from main
with 0
as return value.