Created
December 1, 2015 16:43
-
-
Save arbalest/c9a80bab2c0fa1ffcd86 to your computer and use it in GitHub Desktop.
Simple example demonstrating function pointers and how different functions could be assigned to instances of the same struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
/** | |
* Example demonstrating function pointers in a struct that can be | |
* assigned on a per-type basis (inspired by Quake 3 source's g_local.h's gentity_s type) | |
*/ | |
typedef struct gscreen_s gscreen_t; | |
typedef struct ggame_s ggame_t; | |
struct ggame_s { | |
int width; | |
int height; | |
}; | |
struct gscreen_s { | |
int id; // A normal struct property | |
void (*draw)(gscreen_t* theScreen, float delta); // A function pointer that can be assigned and called, | |
// where draw is the name, int is the return type, and delta is a param. | |
}; | |
void ScreenDraw_Main(gscreen_t* theScreen, float delta) { | |
printf("Drawing #%d with delta %f\n", theScreen->id, delta); | |
} | |
int main(void) { | |
// Typical struct usage | |
gscreen_t mainScreen; | |
mainScreen.id = 10; | |
mainScreen.draw = ScreenDraw_Main; | |
printf("Main Screen ID: %d\n", mainScreen.id); | |
mainScreen.draw(&mainScreen, 1.25f); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment