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.
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.
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.
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.
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.
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)
http://picasaweb.google.com/lh/photo/v2hBpl6D-soIdBXUOmAeMw?feat=directlink
On the left is shown the result of using registers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With