Re: [SLUG] [PIG] call a function without knowing its name in C

From: Levi Bard (taktaktaktaktaktaktaktaktaktak@gmail.com)
Date: Tue May 30 2006 - 12:53:09 EDT


You don't need a hashtable for this:

--
#include <stdio.h>

void a(); void b(); void c();

int main(int argc, char **argv){ void (*functions[3])(void); char funcname='\0';

if(argc != 2){ printf("Usage: %s function\n",argv[0]); return 1; }//if wrong usage

funcname=argv[1][0];

if(funcname<'a' || funcname>'c'){ printf("Invalid function: %s\n",argv[1]); return 1; }//if invalid function

functions[0]=&a; functions[1]=&b; functions[2]=&c;

functions[funcname-'a'](); return 0; }//main

void a(){ printf("a\n"); }

void b(){ printf("b\n"); }

void c(){ printf("c\n"); } --

You can keep track of relationship of the pointers to the array with an enum or a switch or however you like.

I really do love glib, though, and tend to use it for any nontrivial C project.

-- Tcsh: Now with higher FPS! http://www.gnu.org/philosophy/shouldbefree.html ----------------------------------------------------------------------- This list is provided as an unmoderated internet service by Networked Knowledge Systems (NKS). Views and opinions expressed in messages posted are those of the author and do not necessarily reflect the official policy or position of NKS or any of its employees.



This archive was generated by hypermail 2.1.3 : Fri Aug 01 2014 - 19:33:44 EDT