-1

Is there any difference between using function pointer array and switch. ı wrote a code like this

// Declaritons of add-substract-multiply funcitons

void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply}; 
unsigned int ch, a = 15, b = 10; 

printf("Enter Choice: 0 for add, 1 for subtract and 2 "
        "for multiply\n"); 
scanf("%d", &ch); 

if (ch > 2) return 0; 

(*fun_ptr_arr[ch])(a, b); 

and ı wonder what would be better here this code or using a switch ? (in terms of performance btw)

Oğuzhan Aslan
  • 166
  • 2
  • 10
  • 6
    In terms of performance? You'll have to benchmark it. My guess is that the difference in performance will be orders of magnitude below the runtime of your IO bound `printf` and `scanf` calls. Generally the `fun_ptr_arr[ch]` has constant runtime and the `switch` can compile into a jump table, which also has a constant runtime. – Blaze Nov 08 '19 at 11:02
  • 1
    Note that you check if `ch` is greater than 2, but you should check if it's less than `0` as well (or stop using signed integers when you should be using an unsigned one!) – ikegami Nov 08 '19 at 11:08
  • You're not checking for negative values here. If you did, then both of them are *equal* in external behaviour and it depends on the compiler implementation. See [as-if rule](https://stackoverflow.com/questions/15718262/what-exactly-is-the-as-if-rule). – Antti Haapala -- Слава Україні Nov 08 '19 at 11:09
  • You probably shouldn't bother, the difference is most likely so small that it's not worth worrying about. And also compilers are smart nowadays and they might do optimisationsyou wouldn't even imagine. – Jabberwocky Nov 08 '19 at 11:17

1 Answers1

0

A switch statement with adjacent numbers are often optimized to a function pointer look-up table internally.

Historically, compilers were bad at this and function pointer tables were always faster back in the days. Nowadays performance shouldn't be an argument for either version. In fact, one drawback with a manual function pointer table is that the compiler won't be able to inline the functions, something it can otherwise do when optimizing a switch.

So you shouldn't use the function pointer version because it is faster/slower, but rather because it can improve readability and maintenance of the code.

It is for example common practice to use such function pointer tables when implementing finite state machines. Complex switch statements on the other hand, are hard to read and there's various quirks with the syntax, such as the missing break bug etc.

Finally, you can improve the readability of your code if you write like this instead:

typedef void operation_t (int op1, int op2);  // function type

operation_t* const op_array[] = {add, subtract, multiply}; // read-only function pointer table

op_array[i](a, b); // call specific function
Lundin
  • 195,001
  • 40
  • 254
  • 396