I
ImpalerCore
When creating an API for a struct in C, one of the questions that
recently came up is how to pass that struct or return a struct from a
function. Often the answer is obvious, to use pointers, particularly
for large structs for performance reasons.
However, as the struct size shrinks, the choice of passing struct by
value or by pointer becomes less clear to me. Let me use a simple
struct as an example.
struct greg_ymd
{
int16_t year;
int8_t month;
int8_t day;
};
I use this struct to represent a date in the gregorian calendar
(fields not offset to start from 0). Let's say that I want to have a
function that adds a certain number of days to this ymd struct. There
are a couple of options that come to mind.
1. struct greg_ymd add_days( const struct greg_ymd ymd, int days );
2. <return type> add_days( struct greg_ymd* pymd, int days );
First of all, what is the performance implications of using struct
pass-by-value for smallish structs?
Is there a rule of thumb of struct size for an interface API that you
convert all struct parameter passing to use pointers?
Have you used struct by value parameter passing or return value at all
in your API design experience?
The struct pass-by-value version of the interface avoids the pesky
NULL pointer argument issue, but still I can't get away from it
completely since I use 'int (*compare_function)( const void* p, const
void* q )' to define the sorting property in my generic containers.
Thanks for your time.
recently came up is how to pass that struct or return a struct from a
function. Often the answer is obvious, to use pointers, particularly
for large structs for performance reasons.
However, as the struct size shrinks, the choice of passing struct by
value or by pointer becomes less clear to me. Let me use a simple
struct as an example.
struct greg_ymd
{
int16_t year;
int8_t month;
int8_t day;
};
I use this struct to represent a date in the gregorian calendar
(fields not offset to start from 0). Let's say that I want to have a
function that adds a certain number of days to this ymd struct. There
are a couple of options that come to mind.
1. struct greg_ymd add_days( const struct greg_ymd ymd, int days );
2. <return type> add_days( struct greg_ymd* pymd, int days );
First of all, what is the performance implications of using struct
pass-by-value for smallish structs?
Is there a rule of thumb of struct size for an interface API that you
convert all struct parameter passing to use pointers?
Have you used struct by value parameter passing or return value at all
in your API design experience?
The struct pass-by-value version of the interface avoids the pesky
NULL pointer argument issue, but still I can't get away from it
completely since I use 'int (*compare_function)( const void* p, const
void* q )' to define the sorting property in my generic containers.
Thanks for your time.