Welcome to the Linux Foundation Forum!

use of "const volatile" variable. [ Not using pointers]

Hi all,

can some one explain, the real-life use of "const volatile" for a variable, which is NOT A POINTER.

I mean, I aware about, "const volatile *some_mem_addr".

But, what about, "const volatile int not_a_pointer;".

As a language feautere, we can declare a variable like above. But, in what exact situation, it can be used?

Thanks,

Comments

  • My favorite use of "const volatile" is a time or ticks counter in embedded apps.

    That is, if I have an interrupt service routine (ISR) that increments an integer once per tick (maybe once per msec), it's convenient and efficient to use the variable directly, without calling a function. But you want to make it safe, so no one accidentally changes it or passes it's address to a function that changes it. Of course the ISR has to cast it to write it (e.g. *(int *)&ticks += 1;).

    An even more popular use is for processor register declarations. Many processors have memory-mapped registers that you can read but not write which are updated by hardware. They're definitely "const" because you can't write them, and they're definitely "volatile" because the hardware can update them at any time.

Categories

Upcoming Training