register variables....

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ashitpro
    Recognized Expert Contributor
    • Aug 2007
    • 542

    register variables....

    Hello again,

    look at the following statements

    register int i;
    int* b = &i; // valid in C++, but not in C

    when we use "register" specifier, it's a request to compiler that to put the variable in fast registers.
    Now, If we assume that "i" has got stored in register, I am wondering what will be value of "b".
    Do we really have addresses to CPU registers?

    Regards
    Ash
  • arnaudk
    Contributor
    • Sep 2007
    • 425

    #2
    The compiler doesn't have to honour your request for a CPU register, and as far as I know most modern compilers don't as the speed gained is negligible with modern computers. Also, ANSI C does not allow for taking the address of a register object but this restriction does not apply to C++.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      Note since the compiler is free to choose if it honours the register keyword and if you take the address of a variable it must be in an addressable location and most processor registers are not addressable locations.

      So using C++ if you take the address of a register variable the most likely outcome is that the compiler will choose to place the variable in memory anyway so that it can be addressed.

      TBH the register keyword really exists from before the time of optimising compilers when the programmer had to hand optimise the code as a way of indicating to the compiler which variable to place in registers. Today it is best to let the optimiser make this decision, it is likely to make a better decision that you.

      Comment

      Working...