Register variables
We can specify any variable as a register variable in a C program. What this does is it specifies to the compiler that we will be using this variable heavily in our program and if possible to place that variable in a register of the CPU. If done this will significantly increase the speed of your program.
register int x; register float y;
You can declare as many variables as you want as register variables. However the catch is that it is entirely up to the compiler whether to accept your request or not. Another point is that you cannot access the address of any register variable.
Note that it is a good idea to place variables which are counters like “i” in for(i=0; i<1000; i++).
Volatile variables
By indicating that a variable is volatile, we inform the compiler that the value of that variable can change at any time and so it should not apply optimization techniques on it. This can be explained for memory mapped peripherals.
It is quite common to map a peripheral register to memory and then access it via a C program. Suppose you have a program which reads from a hardware register the status of a particular hardware. Say you want to know whether the red LED is turned on or off.
main()
{
int *ptr_red_led = &0x1234;
int led_status;
led_status = *ptr_red_led;
led_status = *ptr_red_led;
}
What happens in this case if compiler optimization is enabled, is that the compiler sees the two lines and feels that they are the same without any change in *ptr_red_led and so it is sufficient to use just one statement. This is wrong and it will produce wrong output as the value in *ptr_red_led can change anytime the hardware changes it’s status.
The correct way is to use the “volatile” keyword for the led_status variable as
main()
{
int *ptr_red_led = &0x1234;
volatile int led_status;
led_status = *ptr_red_led;
led_status = *ptr_red_led; /* checking again */
}

