Pointer declared as constant as well as volatile

前端 未结 6 943
北海茫月
北海茫月 2021-01-31 07:04

While reading I came across this type of declaration and the following line -

const volatile char *p=(const volatile char *) 0x30;
6条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 07:54

    First, let me quote the example from C11 standard, chapter §6.7.3, Type qualifiers

    An object declared

    extern const volatile int real_time_clock;

    may be modifiable by hardware, but cannot be assigned to, incremented, or decremented.

    Also, related footnote (134),

    A volatile declaration may be used to describe an object corresponding to a memory-mapped input/output port or an object accessed by an asynchronously interrupting function. Actions on objects so declared shall not be "optimized out" by an implementation or reordered except as permitted by the rules for evaluating expressions.

    That means, the value of the variable can be modified by the hardware (through the memory-mapping), but cannot be modified "programatically".

    So, the advantage is twofold here,

    • The value whenever used, will be read from the memory (cache-ing not allowed), giving you the latest updated value (if updated).
    • The value, cannot be altered, (written over) intentionally or unintentionally by the program.

提交回复
热议问题