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
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.