[ACCEPTED]-when to use registers in C?-cpu-registers

Accepted answer
Score: 19

How did you time this? In practice, register usually 9 does nothing. It's a piece of cruft from 8 when compiler technology was extremely primitive 7 and compilers couldn't figure out register 6 allocation themselves. It was supposed 5 to be a hint to allocate a register to that 4 variable and was useful for variables used 3 very frequently. Nowadays, most compilers 2 simply ignore it and allocate registers 1 according to their own algorithms.

Score: 13

register gives the compiler a hint to place the 7 variable in a register instead of memory/stack 6 space. In some cases, there won't be enough 5 registers for every variable you place this 4 keyword on so placing it on too many variables 3 can force some of the others out of registers 2 again.

This is just a hint, though, and the 1 compiler doesn't have to take it.

Score: 5

In gcc, register is definitely not ignored, unless 5 you specify optimization options. Testing 4 your code with something like this

unsigned int array[10];

int n;

#define REG register

int main()
{
    REG unsigned int a, b, c;

    for (n = 0; n < 10; ++n){
        c = a + b;
        b = a;
        a = c;
        array[n] = c;
    }
}

you obtain 3 (depending on whether REG is defined or 2 empty)

diff http://picasaweb.google.com/lh/photo/v2hBpl6D-soIdBXUOmAeMw?feat=directlink

On the left is shown the result of 1 using registers.

Score: 1

There are a limited number of registers 8 available, so marking everything as register 7 won't put everything in registers. Benchmarking 6 is the only way to know if it's going to 5 help or not. A good compiler should be 4 able to figure out what variables to put 3 into registers on its own, so you should 2 probably benchmark some more before you 1 decide that the register keywords helps.

Score: 0

The idea of using register is, your variable 6 is used extremely often. If there is any 5 operation with your variable, it will be 4 copied to a register anyway. So counter 3 (index variables) are candidates for this 2 modifier. In the example of Diego Torres Milano from Jan 15 1 '10 at 1:57 I would make it this way:

unsigned int array[10];    

int main()
{
    register int n;
    unsigned int a = 1, b = 2, c;

    for (n = 0; n < 10; ++n){
        c = a + b;
        b = a;
        a = c;
        array[n] = c;
    }
}

More Related questions