newbie_developer93
newbie_developer93

Reputation: 47

function pointer containing the struct itself as parameter being inside the same struct

typedef struct
{
    int x1,y1,x2,y2;
    int (*division_mode_x)(int i,int x1,int x2,SpriteGrid grid);
    int (*division_mode_y)(int i,int y1,int y2);
}SpriteGrid;

Do you think this is a valid way to use function pointers inside struct?
Note : Please don't say try and see it for yourself. There is no problem with compilation. I just wanna know if this is a standard property of the C language. Will it also compile in other compilers?

Upvotes: 0

Views: 216

Answers (1)

Petr Skocik
Petr Skocik

Reputation: 60068

It doesn't compile on gcc, clang or tinycc, and it shouldn't. Before the typedef ends, SpriteGrid is not a thing so you can't use it. Forward declaring the struct (with a tag) and the typedef should fix it.

typedef struct SpriteGrid SpriteGrid; 
typedef struct SpriteGrid /*this typedef is redundant now*/
{
    int x1,y1,x2,y2;
    int (*division_mode_x)(int i,int x1,int x2,SpriteGrid grid);
    int (*division_mode_y)(int i,int y1,int y2);
}SpriteGrid;

Alternatively, you can do

typedef struct SpriteGrid
{
    int x1,y1,x2,y2;
    //without the forward typedef `SpriteGrid` isn't usable
    //here yet, but `struct SpriteGrid` is 
    int (*division_mode_x)(int i,int x1,int x2,struct SpriteGrid grid);
    int (*division_mode_y)(int i,int y1,int y2);
}SpriteGrid;

relying on the fact that a tag becomes usable immediately after struct tag.

Upvotes: 2

Related Questions