Search code examples
ccpu-registersstorage-class-specifier

How many registers are used when a variable is declared using register storage class?


My question is simply, how many registers will a C compiler use for a variable declared using register storage class as : register int a. I have read this answer How many register and what kind of register are available for the storage class REGISTER in c language but could not understand much. I know it can be implementation dependent, but then this registers are limited, so when would the compiler ignore the declaration or will it generate an error?


Solution

  • C11 still supports register:

    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.

    In notes:

    The implementation may treat any register declaration simply as an auto declaration.

    So how many registers will be used? One possible answer is 'none' because the keyword may be ignored.

    That said, in practice it's very rare for an implementation on any modern platform to define intwith a width that is wider than width of a typical platform 'word'. So if an implementation respects register int a; it's unlikely register int a will be allocated to more than one register and register int a may be 0,1 or 2 registers.

    Of course on some hardware not all registers are the same size and sometimes different instructions treat registers as separate or joined. How many registers may not be meaningful.

    As others point out use of the keyword is widely discouraged in C. Indeed its meaning now removed from C++ (though the keyword retained as reserved).

    I think that would be draconian in C which still looks to micro-controller environments where programmers come closest to want to dictate such details.

    All that said 'back in the day' (25 years ago) I worked with a compiler that ignored register but allocated the first 2 (I think) declared variables used as loop counters to registers and in the case in question the third loop in the function was longest and performance noticeably improved by declaring the big loop index first.

    That all seems a very long time ago and no one should take it as the modern experience.