I am reading this question about inline on isocpp FAQ, the code is given as
void f()
{
int x = /*...*/;
int y = /*...*/;
int z = /*...*/;
// ...code that uses x, y and z...
g(x, y, z);
// ...more code that uses x, y and z...
}
then it says that
Assuming a typical C++ implementation that has registers and a stack, the registers and parameters get written to the stack just before the call to
g(), then the parameters get read from the stack insideg()and read again to restore the registers whileg()returns tof(). But that’s a lot of unnecessary reading and writing, especially in cases when the compiler is able to use registers for variablesx,yandz: each variable could get written twice (as a register and also as a parameter) and read twice (when used withing()and to restore the registers during the return tof()).
I have a big difficulty understanding the paragraph above. I try to list my questions as below:
- For a computer to do some operations on some data which are residing in the main memory, is it true that the data must be loaded to some registers first then the CPU can operate on the data? (I know this question is not particularly related to C++, but understanding this will be helpful to understand how C++ works.)
- I think
f()is a function in a way the same asg(x, y, z)is a function. How comex, y, zbefore callingg()are in the registers, and the parameters passed ing()are on the stack? - How is it known that the declarations for
x, y, zmake them stored in the registers? Where the data insideg()is stored, register or stack?
PS
It's very hard to choose an acceptable answer when the answers are all very good(E.g., the ones provided by @MatsPeterson, @TheodorosChatzigiannakis, and @superultranova) I think. I personally like the one by @Potatoswatter a little bit more since the answer offers some guidelines.