Monday, February 15, 2010

C/C++ Array of Functions

Oh, never thought of it? well, this is actually not array of functions, this is array of function pointer. You know, in C/C++, pointers are very powerful tools for accessing and allocating memory, and anything that has a logical entity in any type of memory, a pointer can access it pretty easily and this feature made all other languages jealous that they say allowing pointers are threat-full, lolzzz....

Well, here is a simple code presented that shows the use of such an array. Actually, we all know, like a character array s[100], s is the pointer to it, similarly, a function defined as f(int a), f is the pointer to it. Well, enough talk, lets examine the code...

#include <stdio.h>

inline int add(int a, int b) {
return a + b;

inline int sub(int a, int b) {
return a - b;

inline int mul(int a, int b) {
return a * b;

inline int div(int a, int b) {
return a / b;

inline int mod(int a, int b) {
return a % b;

int main() {
int (*func_array[])(int, int) = {&add, &sub, &mul, &div, &mod};
for(int i=0; i<5; i++) printf("%d\n", func_array[i](10, 5));
return 0;

Easy as usual...


  1. you have to use it in system programming and thread creating in C mate :)

  2. Well is there any way to use the index (i) in the body of the function ?? if its possible many things wud be soooooo ez.

  3. @Anna apu, I am now working on posix thread.
    @Munna, I do not know any other way other than passing i as an argument.

  4. hi, i am a novice programmer,
    i start to solve spoj problems,but i couldn't solve some problem.
    i searched in webs and i found your blog accidentally.
    can you help me?

  5. sorry i forgot to write my name & e-mail
    if you can help me please send me an e-mail