This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Volatile declaration

Should I be using the "volatile" declaration with the Keil C compiler? It hasn't made a difference so far - as far as I can tell (which may or may not mean anyting). The manuals make no reference to it one way or the other.

Parents Reply Children
  • Any variable which can be changed by something outside of a very narrow "local" view of the immediate code should be declared volatile. This includes variables shared with other tasks and variables shared with interrupt handlers, as well as addresses that overlay hardware addresses and might be updated by the hardware.

    Imagine yourself as the code generator producing instructions for a particular line of C, and ask yourself if you would know that a task switch occurred, or if an interrupt occurred, and so on. Volatile is the hint from the programmer to the code generator that it can't be sure the value hasn't changed by some means outside of its scope, and thus must reload the variable, avoid optimizing out apparently redundant writes, and so on.

    (This is in general true of all compilers, not just Keil. It's the standard meaning of volatile, and why the keyword exists.)

  • "Any variable which can be changed by something outside of a very narrow "local" view of the immediate code should be declared volatile. This includes variables shared with other tasks and variables shared with interrupt handlers, as well as addresses that overlay hardware addresses and might be updated by the hardware."

    There are additional considerations when preemptible task switching and interrupts are used. In these situations volatile will not help (but won't necessarily hurt). When manipulating variables of more than one byte in size, you (the coder) have to guaranty mutually exclusive access, since the MCU can't modify multi-byte data objects atomically. Even with 1-byte data objects, you've got to know whether the manipulation is atomic by examining the compiler output.

  • Well, of course. Under RTX51Tiny, if the pre-emptive task-switching is turned off then it can't change tasks unless allowed to by an os_switch_task or os_wait call.

  • Well, of course. Under RTX51Tiny, if the pre-emptive task-switching is turned off then it can't change tasks unless allowed to by an os_switch_task or os_wait call.

  • "Well, of course.

    Sorry to have offended you by stating the obvious.