I would like to know what happens in memory when I use arithmetics operators like:
int i;
i = 5 + 3;
Will the values 5 and 3 be automatically put into the stack temporarily (like if some static variables were automatically created for them)? I suppose they need to exist somewhere for the addition to happen, so where?
What happens when there is a function call involved?
i = 5 + f(3);
Is the argument 3 passed t开发者_运维技巧o f stored somewhere? And what about the return value of f (say f returns an int)?
Many thanks,
Your first example will be evaluated at compile-time (see http://en.wikipedia.org/wiki/Constant_folding), so let's ignore that one.
In the case of something like i = f(3) + g(5)
, the compiler has many choices on how to implement this, depending on the particular platform you're working on. It may put things in registers, or on the stack, or even elsewhere, as it sees fit.
It's not required by the C spec that those values be put into memory. The implementation can keep them in registers and never store them on memory for carrying out the addition or the compiler can even rewrite 5 + 3
into 8
and don't do any addition at all at runtime. Any real implementation does it like that.
In the language theory, in fact, 5
and 3
aren't referring to memory. They are values (instead of merely representing a location where a value can be fetched from). You can easily see that by trying to write &5
. It won't work - there is no address you could receive.
Have a look at the compiler switches. Possible there is the possibility to keep/generate the intermediary assembler code. There you see exaclty what happens with your code.
The compiler will allocate temporary variables as it needs them. This is done at compile/optimization time. Not at runtime (for C programs, anyway). Most likely, for your example, the result of the
5 + 3
or
5 + f(3)
will be stored in a register and the value of the register will be copied to the location of i.
When you have expression such as i = 5 + 3
there's no needing to put the operands on the stack. The compiler will translate that into something similar to:
mov eax, 5 // load first operand
add eax, 3 // compute the sum
mov [ebp - 4], eax // and store it
The operands are hard-coded in the instruction. Some compiler might decide to make this code like int i = 8
.
i = 5 + f(3)
In this case 3 will be pushed on the stack because f
has to be called, but its return value is (usually) stored in eax
. This assembly code might be a good translation:
push 3 // f's argument
call f // call f, return value is in eax
add eax, 5 // compute the sum
mov [ebp - 4], eax // and save in i
精彩评论