Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward declaration of function pointer typedef

I've run into a peculiar problem. It might be best to just show you what I'm trying to do and then explain it.

typedef void functionPointerType ( struct_A * sA );

typedef struct
{
    functionPointerType ** functionPointerTable;
}struct_A;

Basically, I have a structure struct_A with a pointer to a table of function pointers, who have a parameter of type struct_A. But I'm not sure how to get this compile, as I'm not sure how or if can forward declare this.

Anyone know how this could be achieved?

edit: minor fix in code

like image 932
mario87 Avatar asked Mar 25 '13 22:03

mario87


People also ask

Can I forward declare a typedef?

But you can't forward declare a typedef. Instead you have to redeclare the whole thing like so: typedef GenericValue<UTF8<char>, MemoryPoolAllocator<CrtAllocator> > Value; Ah, but I don't have any of those classes declared either.

Can we use typedef for function pointer?

A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function.

How do you forward a function declaration?

To write a forward declaration for a function, we use a function declaration statement (also called a function prototype). The function declaration consists of the function header (the function's return type, name, and parameter types), terminated with a semicolon. The function body is not included in the declaration.

What is forward declaration in C?

In computer programming, a forward declaration is a declaration of an identifier (denoting an entity such as a type, a variable, a constant, or a function) for which the programmer has not yet given a complete definition.


1 Answers

Forward declare as you suggest:

/* Forward declare struct A. */
struct A;

/* Typedef for function pointer. */
typedef void (*func_t)(struct A*);

/* Fully define struct A. */
struct A
{
    func_t functionPointerTable[10];
};

For example:

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

struct A;

typedef void (*func_t)(struct A*);

struct A
{
    func_t functionPointerTable[10];
    int value;
};

void print_stdout(struct A* a)
{
    printf("stdout: %d\n", a->value);
}

void print_stderr(struct A* a)
{
    fprintf(stderr, "stderr: %d\n", a->value);
}

int main()
{
    struct A myA = { {print_stdout, print_stderr}, 4 };

    myA.functionPointerTable[0](&myA);
    myA.functionPointerTable[1](&myA);
    return 0;
}

Output:

stdout: 4
stderr: 4

See online demo http://ideone.com/PX880w .


As others have already mentioned it is possible to add:

typedef struct A struct_A;

prior to the function pointer typedef and full definition of struct A if it is preferable to omit the struct keyword.

like image 87
hmjd Avatar answered Sep 25 '22 10:09

hmjd