Search code examples
c++runtimesizeof

Why do books say, “the compiler allocates space for variables in memory”?


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 ?


Solution

  • When we hire an architect to design a house, he or she defines the size of the rooms, etc. and informs the workers (labourers) about it. The labourers do the work accordingly. But still we would say "The architect made the house this way" and not "The labourer made the house this way".

    The labourer is just performing the steps defined by the architect. The compiler actually does all the work for checking and defining how much memory is to be allocated, etc. at run time and then those instructions are just followed.