6
#include <stdlib.h>

inline int f0(int a) {
  return a*a;
}

inline int f1(int a) {
  return a*a*a;
}

int main() {
  int (*f)(int);
  f = rand()%2 ? f0 : f1;
  return f(rand());
}

So with gcc, asm file generated is same with or without inline. Is it same with any code with function pointers?

  • 1
    Note that most compilers, including gcc, don't really care about your `inline` when the decide whether they inline something. It definitely can ignore it and I'd be surprised if presence of `inline` had much influence on the heuristic that decides that. –  Sep 04 '11 at 20:46

1 Answers1

6

Function pointers cannot be inlined unless their value is fully decidable at compile time. Your case is not decidable.

Most of the time function pointers will never be inlined, even if the compiler can see which function is in the function pointer.

Yann Ramin
  • 32,895
  • 3
  • 59
  • 82
  • 1
    I agree with most of this. However, `f0` and `f1` *could* be inlined here (`if (rand%2) { /* code for f0 */ } else { /* code for f1 */ }`). But I doubt any compiler would have a heuristic to spot this kind of thing. – Oliver Charlesworth Sep 04 '11 at 21:19