R – Will GCC inline a function that takes a pointer

cgccinline()optimizationpointers

I have a function which operates on piece of data (let's say, an int), and I want to change it in place by passing a reference to the valule. As such, I have the function: void myFunction(int *thing) { ... }. When I use it I call it thus: myFunction(&anInt).

As my function is called frequently (but from many different places) I am concerned about its performance. The reason I have refactored it into a function is testability and code reuse.

Will the compiler be able to optimize the function, inlining it to operate directly on my anInt variable?

I hope you'll take this question in the spirit in which it's asked (i.e. I'm not prematurely worrying about optimisation, I'm curious about the answer). Similarly, I don't want to make it into a macro.

Best Answer

GCC is quite smart. Consider this code fragment:

#include <stdio.h>

void __inline__ inc(int *val)
{
    ++ *val;
}

int main()
{
    int val;

    scanf("%d", &val);

    inc(&val);

    printf("%d\n", val);

    return 0;
}

After a gcc -S -O3 test.c you'll get the following relevant asm:

...
call    __isoc99_scanf
movl    12(%rsp), %esi
movl    $.LC1, %edi
xorl    %eax, %eax
addl    $1, %esi
movl    %esi, 12(%rsp)
call    printf
...

As you can see, there's no need to be an asm expert to see the inc() call has been converted to an increment instruction.