Optimize and inline calls via function pointer : <p>I wanted to see if the compiler was clever enought to inline calls via a function pointer.</p>

<p>If I compile using gcc 4.8 with any -Os or -O2 then the compiler will inline apply1 and apply2 into main, but will additionally for apply2 it removes the indirect call via function pointer and inlines add1 into the code too. In apply1 it does not. In general it seems to be the case that declaring my function static allows this optimization within it, but non static does not.</p>

<p>Is there any fundemental difference that explains this?</p>

<p>This is now mostly for curiosity but motivated by some high performance code I need to write and so would like to understand what might provoke this difference.</p>

<p>Although this code is C I get the same if I compiler as C++ too.</p>

<pre><code>#include &lt;stdio.h&gt;

int add1(int a)
{
    return a + 1;
}

void apply1(int lower, int upper, int (* func)(int))
{
    for (int i = lower; i &lt; upper; i++)
    {
        printf("%d = %d\n", i, func(i));
    }
}

static void apply2(int lower, int upper, int (* func)(int))
{
    for (int i = lower; i &lt; upper; i++)
    {
        printf("%d = %d\n", i, func(i));
    }
}

int main()
{
    apply1(0, 10, add1);
    apply2(0, 10, add1);
}
</code></pre>
