Why do books say, “the compiler allocates space fo

2019-02-06 15:39发布

Why do books say, "the compiler allocates space for variables in memory". Isn't it the executable which does that? I mean, for example, if I write the following program,

#include <iostream>
using namespace std;

int main()
{
   int foo = 0;
   cout<<foo;
   return 0;
}

and compile it, and get an executable (let it be program.exe), now, if I run program.exe, this executable file will itself command to allocate some space for the variable foo. Won't it ? Please explain why books keep on saying, "the compiler will do this...do that" whereas actually, the compiled executable does that.

Adding another related question to this question, why is sizeof called a compile-time operator ? Isn't it actually a run-time operator ?

7条回答
乱世女痞
2楼-- · 2019-02-06 16:31

The compiler generates machine instructions and works out what memory address local variables will occupy. Each local variable is given an address relative to the top of the stack, eg foo would be assumed to be at memory address stack_pointer. If you had a variable foo2 it would be placed at address stack_pointer + 4 where 4 is the size of an int.

When the local variable foo is accessed, the compiler will substitute the address held in stack_pointer. The hardware has a special stack_pointer register which always points to the top of the current stack.

The compiler knows what size each variable is because it is responsible for looking at struct or class declarations and working out how it is laid out in memory. So sizeof is known at compile time and is treated as a constant expression. Primitive types like int are known to be of a certain size, eg sizeof(int) is 4.

查看更多
登录 后发表回答