Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to use registers in C?

I have something like this

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

what it does, it doesn't matter. The code runs quickly the way it is now, slower if the register keyword is removed. However, when I add in register before int n, it actually runs slower than now, but faster than if no registers is used.

Can someone explain this to me? Thanks.

like image 302
SuperString Avatar asked Jan 15 '10 00:01

SuperString


People also ask

When should the register modifier be used?

When should the register modifier be used? Does it really help? The register modifier hints to the compiler that the variable will be heavily used and should be kept in the CPU's registers, if possible, so that it can be accessed faster.

Why a register variable should not be used?

In the end, use of register variables could actually result in slower execution. Register variables should only be used if you have a detailed knowledge of the architecture and compiler for the computer you are using.

What are registers in C?

In the C programming language, register is a reserved word (or keyword), type modifier, storage class, and hint. The register keyword was deprecated in C++, until it became reserved and unused in C++17.

When should I use volatile in C?

Volatile is used in C programming when we need to go and read the value stored by the pointer at the address pointed by the pointer. If you need to change anything in your code that is out of compiler reach you can use this volatile keyword before the variable for which you want to change the value.


1 Answers

In gcc, register is definitely not ignored, unless you specify optimization options. Testing 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 (depending on whether REG is defined or empty)

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

On the left is shown the result of using registers.

like image 117
Diego Torres Milano Avatar answered Sep 28 '22 08:09

Diego Torres Milano