Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Volatile tells the compiler not to optimize anything that has to do with the volatile variable. </p> <p>There is only one reason to use it: When you interface with hardware. </p> <p>Let's say you have a little piece of hardware that is mapped into RAM somewhere and that has two addresses: a command port and a data port:</p> <pre><code>typedef struct { int command; int data; int isbusy; } MyHardwareGadget; </code></pre> <p>Now you want to send some command:</p> <pre><code>void SendCommand (MyHardwareGadget * gadget, int command, int data) { // wait while the gadget is busy: while (gadget-&gt;isbusy) { // do nothing here. } // set data first: gadget-&gt;data = data; // writing the command starts the action: gadget-&gt;command = command; } </code></pre> <p>Looks easy, but it can fail because the compiler is free to change the order in which data and commands are written. This would cause our little gadget to issue commands with the previous data-value. Also take a look at the wait while busy loop. That one will be optimized out. The compiler will try to be clever, read the value of isbusy just once and then go into an infinite loop. That's not what you want. </p> <p>The way to get around this is to declare the pointer gadget as volatile. This way the compiler is forced to do what you wrote. It can't remove the memory assignments, it can't cache variables in registers and it can't change the order of assignments either:</p> <p>This is the correct version:</p> <pre><code> void SendCommand (volatile MyHardwareGadget * gadget, int command, int data) { // wait while the gadget is busy: while (gadget-&gt;isbusy) { // do nothing here. } // set data first: gadget-&gt;data = data; // writing the command starts the action: gadget-&gt;command = command; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload