Search code examples
ccompiler-constructioncpu-architecturecpu-registers

why does compiler store variables in register?


Hi I have been reading this kind of stuff in various docs

register

Tells the compiler to store the variable being declared in a CPU register.

In standard C dialects, keyword register uses the following syntax:

register data-definition;

The register type modifier tells the compiler to store the variable being declared in a CPU register (if possible), to optimize access. For example,

register int i;

Note that TIGCC will automatically store often used variables in CPU registers when the optimization is turned on, but the keyword register will force storing in registers even if the optimization is turned off. However, the request for storing data in registers may be denied, if the compiler concludes that there is not enough free registers for use at this place.

http://tigcc.ticalc.org/doc/keywords.html#register

My point is not only about register. My point is why would a compiler stores the variables in memory. The compiler business is to just compile and to generate an object file. At run time the actual memory allocation happens. why would compiler does this business. I mean without running the object file just by compiling the file itself does the memory allocation happens in case of C?


Solution

  • The compiler is generating machine code, and the machine code is used to run your program. The compiler decides what machine code it generates, therefore making decisions about what sort of allocation will happen at runtime. It's not executing them when you type gcc foo.c but later, when you run the executable, it's the code GCC generated that's running.

    This means that the compiler wants to generate the fastest code possible and makes as many decisions as it can at compile time, this includes how to allocate things.