Search code examples
cvariablesassemblymicroprocessors

How can there be so many register variables, with such a limited number of registers?


I was fooling around with C and I realized, by rights, if I declared a bunch of register variables, wouldn't the values be overwritten? From what I can tell from assembly, there aren't a ton of registers in the microprocessor, not enough to satisfy the demand I created. How does C keep all the values?


Solution

  • There's no requirement that all variables declared with register must be kept in CPU registers.

    Here's what the C standard says:

    A declaration of an identifier for an object with storage-class specifier register suggests that access to the object be as fast as possible. The extent to which such suggestions are effective is implementation-defined.

    Reference: ISO C11 N1570 draft, 6.7.1 paragraph 6. Note that it doesn't even mention CPU registers.

    A conforming compiler could simply ignore all register keywords (aside from imposing some restrictions on taking the address of register objects).

    In practice, most compilers will simply place as many register variables in CPU registers as they can.

    And in fact a modern optimizing compiler is likely to be better at register allocation than most programmers are -- especially since they can recompute register mappings every time you recompile your program after modifying it.

    The common wisdom these days is that the register keyword doesn't provide much benefit.