Can gcc inline an indirect function call through a constant array of function pointers?

1.8k views Asked by At

Let's say we have this code:

inline int func_2 (int a, int b) {
  return time() + a * b;
}

int main (void) {
  int x = (int (*[])(int, int)){func_1, func_2, func_3}[1](6, 7);
}

Can gcc be somehow tricked to really inline the indirect calls to func_*?

After compiling the code with -O2 and -O3, I could still spot a call func_2 instruction in the assembly output.

I know this hairy expression can be converted into a bulky switch statement with inlined calls for each case, but I prefer the former for its compactness.

1

There are 1 answers

2
Laurent G On BEST ANSWER

if it does not hurt you to allocate some space in the data segment, you can try like this:

static int func_2 (int a, int b) {
    return time() + a * b;
}

static int (* const ftab[])(int,int) = {func_1, func_2, func_3};

int foo (void) {
    return ftab[1](6,7);
}

my gcc 4.4.5 correctly inlines the function with -O2.

The aggregate initializer inside the code of the function does not forward the constant as we expect, I don't know wheter it's a gcc bug or our misunderstanding of some C rule.