2

I've read that the volatile keyword in C is used to specify to the compiler that the value of a declared variable or function may be changed without the program itself changing it.

Given that my programs are always run by an Operating System (which can change these values without the program changing them), is there any reason not to use the volatile keyword in all variable and function declarations?

  • 5
    "Given that my programs are always run by an Operating System (which can change these values without the program changing them)". Under what circumstance do you think the OS would randomly change the variable values in your program? – kaylum May 24 '20 at 07:29
  • 1
    Using `volatile` where it is not expressly needed is always wasteful, and can also be dangerous if based on the misconception that it provides some kind of thread safety. – dxiv May 24 '20 at 07:36
  • @kaylum I don't think that the Operating System would do it, but it is possible, isn't it? – Joseph Pilliner May 25 '20 at 06:22
  • @dxiv can you give me an example of how it might be dangerous? – Joseph Pilliner May 25 '20 at 06:23
  • 1
    @JosephPilliner As I wrote, it's only dangerous if you have misplaced expectations of what it does and was meant for - threads not being among them. See for example [Why is volatile not considered useful in multithreaded C or C++ programming?](https://stackoverflow.com/questions/2484980/why-is-volatile-not-considered-useful-in-multithreaded-c-or-c-programming) or [When to use volatile with multi threading?](https://stackoverflow.com/questions/4557979/when-to-use-volatile-with-multi-threading). – dxiv May 25 '20 at 06:36

1 Answers1

3

The OS will not change your variables unless you ask it to do that (by some function call that involves the OS).

Don't use volatile all over. It will reduce program performance because it forces all variables to be updated from memory all the time. So you won't get benefit from the cache, nor from the normal compiler optimization.

Actually, it's pretty seldom that you will use volatile. Read this answer from another question to learn more: https://stackoverflow.com/a/246148/4386427

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • `volatile` typically does not pierce memory caching. What constitutes “access” for `volatile` objects is defined by each C implementation, not the C standard, but it is typically a routine memory access including normal caching. So the effect of `volatile` is, for loads, to tell the compiler not to use a value it loaded previously (and may have in some register or partially computed subexpression). If caching must be disabled, that is typically handled separately, as a part of memory map settings. E.g., the part of address space mapped to device interfaces will be marked no-cache. – Eric Postpischil May 24 '20 at 10:55