title: Volatile function
body: <p><strong>Summary</strong>: What does the keyword <code>volatile</code> do when applied to a function declaration in C and in C++?  </p>
  
  <p><strong>Details</strong>:</p>
  
  <p>I see that it's possible to compile a function that is marked as <code>volatile</code>.  However, I'm not sure what compiler optimization (if any) this prevents.  For instance I created the following test case:</p>
  
  <pre><code>volatile int foo() {
    return 1;
  }
  
  int main() {
    int total = 0;
    int i = 0;
    for(i = 0; i &lt; 100; i++) {
      total += foo();
    }
  
    return total;
  }
  </code></pre>
  
  <p>When I compile with <code>clang -emit-llvm -S -O3 test.c</code> (gcc would also work but the llvm IR is more readable in my opinion) I get:</p>
  
  <pre><code>target triple = "x86_64-unknown-linux-gnu"
  
  define i32 @foo() #0 {
    ret i32 1
  }
  
  define i32 @main() #0 {
    ret i32 100
  }
  </code></pre>
  
  <p>So obviously the compiler was able to optimize away the calls to function <code>foo()</code> so that <code>main()</code> returns a constant, even though <code>foo()</code> is marked as <code>volatile</code>.  So my question is whether <code>volatile</code> does anything at all when applied to a function declaration in terms of limiting compiler optimizations.</p>
  
  <p>(Note my interest in this question is mostly curiosity to understand what <code>volatile</code> does rather than to solve any specific problem.)</p>
  
  <p>(Also I have marked this question as both C and C++ not because I think they are the same language, but because I am interested to know if there are differences in what <code>volatile</code> does in this case in these two languages).</p>