i’m developing a “first” C software for an embedded device.
I would like write code in a oo-style, so i started to use structs.
typedef struct sDrawable {
Dimension size;
Point location;
struct sDrawable* parent;
bool repaint;
bool focused;
paintFunc paint;
} Drawable;
typedef struct sPanel {
Drawable drw;
struct sDrawable* child;
uint16_t bgColor;
} Panel;
I can’t and i don’t want use malloc, so i search the better way to instantiate my structs.
Is this acceptable?
Panel aPanel={0};
void Gui_newPanel(Panel* obj, uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t bgColor) {
// Drw is a macro to cast to (Drawable*)
Drw(obj)->repaint = true;
Drw(obj)->parent= NULL;
Drw(obj)->paint = (paintFunc) &paintPanel;
Drw(obj)->location=(Point){x, y};
Drw(obj)->size=(Dimensione){w, h};
obj->child = NULL;
obj->bgColor = bgColor;
}
void Gui_init(){
Gui_newPanel(&aPanel, 0, 0, 100, 100, RED);
}
UPDATE
In the first one, i have to initialize struct like Panel aPanel={0}; to pass its pointer to Gui_newPanel function, or i can only write Panel aPanel; ?
I have tested and both works, but maybe i’m only unlucky…
Or is this a better way?
Panel aPanel;
Panel Gui_newPanel(uint16_t x, uint16_t y, uint16_t w, uint16_t h, uint16_t bgColor) {
// Drw is a macro to cast to (Drawable*)
Panel obj;
Drw(&obj)->repaint = true;
Drw(&obj)->parent= NULL;
Drw(&obj)->paint = (paintFunc) &paintPanel;
Drw(&obj)->location = (Point){x, y};
Drw(&obj)->size = (Dimension){w, h};
obj.child = NULL;
obj.bgColor = bgColor;
return obj;
}
void Gui_init(){
aPanel=Gui_newPanel(0, 0, 100, 100, RED);
}
Which of these methods is preferable?
I am particularly interested in performance and memory usages.
Thanks
Returning
structs by value can incur overhead of copying the struct members, although the compiler will often be smart enough to optimise this out. If you’re concerned as to the overhead, you should profile the relative performance of the two approaches.Also, check whether the target compiler for the device is actually able to support returning structs – some very old compilers don’t support returning or assignment of structs.
If you have a reasonably modern compiler, you may be able to return a
structliteral directly, which will be efficient: