Will GCC inline a function that takes a pointer? Will GCC inline a function that takes a pointer? c c

Will GCC inline a function that takes a pointer?


One way to find out if the function is inlined is to use -Winline gcc option:

-Winline  Warn if a function can not be inlined and it was declared as inline.  Even with this option, the compiler will not warn about failures to inline  functions declared in system headers.  The compiler uses a variety of heuristics to determine whether or not to  inline a function. For example, the compiler takes into account the size  of the function being inlined and the amount of inlining that has already  been done in the current function.  Therefore, seemingly insignificant  changes in the source program can cause the warnings produced by -Winline  to appear or disappear.


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_scanfmovl    12(%rsp), %esimovl    $.LC1, %edixorl    %eax, %eaxaddl    $1, %esimovl    %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.


There are two issues here - can the code be optimised, and will it. It certainly can be, but the "will" depends on the mood the optimiser is in. If this is really important to you, compile the code and take a look at the assembly language output.

Also, you seem to be conflating two issues. An inlined function effectively has its body pasted at the call site. Whether or not you are using pointers is neither here nor there. But you seem to be asking if the compiler can transform:

int x = 42;int * p = & x;* p = * p + 1;

into

x = x + 1;

This is much more difficult for the optimiser to see.