Welcome, Guest. Please login or register.

Author Topic: jump tables (-Edit- Eliminating conditional statements :-))  (Read 13667 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show all replies
    • http://www.iki.fi/sintonen/
Re: jump tables
« on: February 21, 2005, 12:18:10 PM »
I won't give you the exact solution, but this should help still:

Code: [Select]

#include <stdio.h>

typedef int (*funcptr_t)(int, char *);

int func1(int x, char *str);
int func2(int x, char *str);
int func3(int x, char *str);

int main(void)
{
  funcptr_t funcarray[3] =
  {
    func1,
    func2,
    func3
  };
  int i;

  for (i = 0; i < 3; i++)
  {
    int ret;

    ret = funcarray[i](i * i + 2, &quot;moo&quot;);
    printf(&quot;ret %d\n&quot;, ret);
  }

  return 0;
}

int func1(int x, char *str)
{
  printf(&quot;func1 x=%d, str=<%s>\n&quot;, x, str);
  return 1;
}

int func2(int x, char *str)
{
  printf(&quot;func2 x=%d, str=<%s>\n&quot;, x, str);
  return 2;
}

int func3(int x, char *str)
{
  printf(&quot;func3 x=%d, str=<%s>\n&quot;, x, str);
  return 3;
}


[EDIT]changed i*i to i*i+2 to make it more obvious the input isn't always the index ;-)[/EDIT]