Combining const & volatile

Discussion in 'General Electronics Chat' started by aamirali, Nov 21, 2012.

  1. aamirali

    Thread Starter Member

    Feb 2, 2012
  2. takao21203

    Distinguished Member

    Apr 28, 2012
    You should try this yourself, and ask concrete questions if you run into trouble.

    "const" means the compiler will in some cases interprete it as to read from ROM.

    However, there is such a case when you read from ROM to RAM.
  3. nsaspook

    AAC Fanatic!

    Aug 27, 2009
    As the article explains 'const' is applied to the location of the pointer and 'volatile' is applied to the data at that pointer location. comm_buffer is a pointer, comm_buffer[0] is the data at that location with a zero uint8_t byte-size offset.

    Code ( (Unknown Language)):
    1. uint8_t const volatile comm_buffer[BUFFER_SIZE];
    Using 'volatile' can be very misleading if not used in a very narrow context 'I/O hardware mainly' as it is not a substitute for proper locking of shared non-atomic data structures. Even in simple non-cached systems only updating 'volatile' structure data in a ISR is not adequate, you usually have to use 'memory barriers' to provide atomic access to data structures larger than the processors native word size.
    Last edited: Nov 21, 2012
  4. takao21203

    Distinguished Member

    Apr 28, 2012
    There is not really a total easy generic answer.

    It depends on the type of pointer.
    Since microcontrollers have both RAM and ROM areas, and some controllers need different instructions for RAM or ROM.

    It is really compiler and chip and data structure specific, very so.

    You have to use the simulator/debugger, and derive the data structures you want in your program, and figure out how to access them correctly.

    Normally predefined data like tables is almost always placed in ROM, although you are free to place in RAM if you wanted to.

    You can also do things like putting together various pointers to ROM areas into a table which also is stored inside the ROM.

    If you want to prevent a write to a hardware register, this is in many cases up to you, as normally nothing will happen if you attempt it. It is kinda like if you try to "read" from an external serial shifting storage register. You'd normally know it does not make sense.

    OP should have a look at this.

    It can be seen there is not really an easy, generic answer in form and length of a "tweet" (twitter message). And if there is such an answer, it will cause other questions, or it won't tell the whole truth.

    Most embedded compilers are not ANSI conform.