comp.lang.c
[Top] [All Lists]

Re: Function pointer tables

Subject: Re: Function pointer tables
From: pete
Date: Fri, 28 Mar 2008 15:00:42 -0500
Newsgroups: comp.lang.c

Bartc wrote:
> 
> I'm having problems with the following code.
> 
> I have a table of function pointers, and a function pointer variable p which
> steps through the functions.
> 
> But I'm not allowed to increment the variable using ++p.
> 
> What's the problem here?
> 
> Also, I may not be interested in returning from any of these functions (each
> will call the next according to some global variable). Any recommended way
> of doing this (throwing away return address) other than a crude asm("pop
> R")?
> 
> Thanks,
> 
> Bart.
> 
> #include <stdio.h>
> #include <stdlib.h>
> 
> void f1(void);
> void f2(void);
> void f3(void);
> void f4(void);
> 
> int main(void)
> {
> void (*table[])(void)={&f1,&f2,&f3,&f4};    /* table of function pointers */
> void (*p)(void);    /* pointer to one of the functions (I hope) */
> 
> p=table[0];
> 
> while(1)
> { (*p)();    /* Call function @p */
>   ++p;    /* COMPILE ERROR HERE */
> };
> 
> }
> 
> void f1(void){puts("F1 CALLED");return;};
> void f2(void){puts("F2 CALLED");return;};
> void f3(void){puts("F3 CALLED");return;};
> void f4(void){puts("F4 CALLED"); exit(0);};

/* BEGIN new.c */

#include <stdio.h>
#include <stdlib.h>

void f1(void);
void f2(void);
void f3(void);
void f4(void);

int main(void)
{
    void (*table[])(void) = {
        f1, f2, f3, f4
    };  
    void (**p)(void);   

    p = table;
    while (p != table + sizeof table / sizeof *table) {
        (*p++)();
    }
    return 0;
}

void f1(void)
{
    puts("F1 CALLED");
}

void f2(void)
{
    puts("F2 CALLED");
}

void f3(void)
{
    puts("F3 CALLED");
}

void f4(void)
{
    puts("F4 CALLED");
}

/* END new.c */

-- 
pete

<Prev in Thread] Current Thread [Next in Thread>
Privacy Policy