title: GCC printf optimization
body: <p>I noticed that GCC is very smart about optimizing <code>printf</code>. For example, <code>printf("")</code> is completely removed from the resulting code. <code>printf("\n")</code> is replaced with <code>putchar('\n')</code>. </p>
  
  <p>I noticed when I compile a very small module like this:</p>
  
  <pre><code>extern "C" int printf(const char *__restrict __format, ...);
  
  void f()
  {
      printf("\n");
  }
  </code></pre>
  
  <p>with <code>gcc -O2</code> the call to <code>printf</code> is replaced with <code>putchar('\n')</code> (don't even need to include any header files).</p>
  
  <p>Generated code:</p>
  
  <pre><code>f():
          mov     edi, 10
          jmp     putchar
  </code></pre>
  
  <p>What is the mechanism that allows those optimizations to be performed? As far as I know standard C++ does not provide any features that allows such optimizations.</p>
  
  <p>Could it be extended for the user functions or is it "hardcoded" in the compiler?</p>
  
  <p>This also means if I wanted to redefine <code>printf</code> with my own implementation the compiler might mess it up. Is it true?</p>