R.D.
R.D.

Reputation: 2631

How do you declare multiple function pointers in a single line without typedeffing?

More of a matter of curiosity than anything. Basically I want to know if it's possible to declare multiple function pointers in a line, something like:

int a = 1, b = 2; 

With function pointers? Without having to resort to typedef.

I've tried void (*foo = NULL, *bar = NULL)(int). Unsurprisingly, this didn't work.

Upvotes: 11

Views: 1656

Answers (2)

vvy
vvy

Reputation: 2073

Try as follows:

void (*a)(int), (*b)(int);

void test(int n)
{
    printf("%d\n", n);
}
int main()
{
    a = NULL;
    a = test;
    a(1);
    b = test;
    b(2);
    return 0;
}

EDIT:

Another form is array of function pointers:

void (*fun[2])(int) = {NULL, NULL};

void test(int n)
{
    printf("%d\n",n);
}
int main()
{
    fun[0] = NULL;
    fun[0] = test;
    fun[0](1);
    fun[1] = test;
    fun[1](2);
}

Upvotes: 13

David Ranieri
David Ranieri

Reputation: 41026

void (*foo)(int) = NULL, (*bar)(int) = NULL;

or as Grijesh says:

int main(void) {
    int a[5], b[55];
    int (*aa)[5] = &a, (*bb)[55] = &b;
    return 0;
}

Upvotes: 5

Related Questions