1

From what I have read on the web and on SO:

const:

  • tells the compiler that the variable must not be changed using program instructions.
  • consequently, the compiler can optimize the code.

volatile:

  • variable is constant but can be change from outside the program.
  • tells the compiler to read the variable's value from memory each time.
  • tells the compiler not to use optimization with this variable.

If my understanding is correct, so volatile is just another kind of const.

so, what does a line like the one below mean?

const volatile char A = 'C';

Shadi
  • 1,701
  • 2
  • 14
  • 27
  • 2
    In addition, volatile means that variable can be updated from other source, not just from CPU (for example, peripheral registers in microcontrollers can be updated from GPIO or anything else), so you need to read them with pointer as volatile. – unalignedmemoryaccess Apr 04 '17 at 14:46
  • 10
    *variable is constant but can be change from outside the program.* Is not right. A volatile variable can be modified. – NathanOliver Apr 04 '17 at 14:47
  • @FrançoisAndrieux Some compilers will put `const` variable to non-volatile memory and doing that may lead to device crash. – unalignedmemoryaccess Apr 04 '17 at 14:48
  • @FrançoisAndrieux so MCUs (for example) have flash and RAM memory. Flash for program flow and ram for variables. If you declare const variable, some compilers (well, linkers) will put this variable into flash memory area as part of program and not in RAM memory. If you do `&constVariable` you may get address from flash space. – unalignedmemoryaccess Apr 04 '17 at 14:51
  • @tilz0R I think you believe I'm advocating that modifying const non-volatile variables is permitted. Perhaps because the separation between the words `non-const` and `volatile` was less than obvious and could be read as non-"const volatile". I'll remove my comment to avoid confusion, and because NathanOliver's the same information. – François Andrieux Apr 04 '17 at 14:58
  • Of course you can modify variables, but you have to be aware, that variable with `const`parameter is in ram. Example where it is easily allowed to modify content: `const char a = 1; char* b = (char *)&a; *b = 2;` – unalignedmemoryaccess Apr 04 '17 at 15:00
  • *"consequently, the compiler can optimize the code."* - That's not the point. You use `const` for correctness, not for speed. – Christian Hackl Apr 04 '17 at 16:42

1 Answers1

10

No, volatile is not "another kind of const". volatile does not mean "variable is constant".

Otherwise, your points are accurate. So, const volatile means:

  1. The programmer is prevented from modifying the object after its initialisation (this is the const part)
  2. External mechanisms may still modify its value, which therefore must be retrieved from "memory" each time a read is requested rather than being cached by optimisations (this is the volatile part)
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055