Search code examples
cstorage-class-specifier

Register vs Auto Storage class?


right now im learning about storage classes here. And he seems to explain the same thing for the auto storage class and the register storage class. The only thing he diffrenciated between the two is that the register storage class is stored in CPU Register.. Are there any diffrences between these storage classes? Any uses of the register storage class? Is Register keyword thier by default on some C Compilers?

register int x = 5;
auto int y = 3;

Solution

  • The register storage class does not imply that the object will be stored in a register. The 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.

    (The quotation is from the N1570 draft of the ISO C standard, section 6.7.1 paragraph 6.)

    Storing the object in a CPU register rather than in memory is one way to accomplish that, but not the only one.

    Modern compilers (at least according to the common wisdom) are probably better than you are at deciding which variables should be stored in registers for speed, so using the register keyword probably won't do anything other than interfere with the compiler's optimization.

    register also makes it illegal to take the address of the object (even if it's stored in memory).

    It's basically a holdover from early compilers (1970s) that didn't perform the sophisticated optimizations modern compilers do. For such a compiler register could significantly improve performance.

    (Modern compilers, I believe, start by assuming that all variables can be allocated in registers, and "spill" them to memory only when necessary, either because the variable's address is needed or because there aren't enough registers available.)