I
ImpalerCore
Writing them in-line would be more error-prone. Making them functions
lets you give each operation a name.
Right, encapsulating the operation as a function assigns a semantic
name to an underlying operation. It is a textbook case of information
hiding. The value of the routine is that if the internal structure
name changes for any reason, the name change only needs to be done to
the access routines, not everywhere in the code. It can provide more
readability in the general case where you may find 'struct->what->does->this->mean'. The compiler is typically clever enough in most cases
to optimize the function call away.
How would a macro be better than an inline function?[...]
I find a macro to be more beneficial when one wants compiler
granularity to enable/disable the function. For access routines to a
data structure, definitely not.
Actually, that's not entirely true. I use macros to access generic
containers with void* where the type information is passed on to
another function that uses 'sizeof (type)'.
\code snippet
void* gc_array_front( struct c_array* array )
{
void* p = NULL;
if ( array->size ) {
p = array->buffer;
}
return p;
}
#define c_array_front( array, type ) ( (type*)
(gc_array_front( (array) )) )
\end snippet
If I store the 'sizeof (type)' in the array structure itself, it's
possible to assert that the internal element size assigned when the
array was allocated matches the size of the type used in the access
function.
\code snippet
void* gc_array_front( struct c_array* array, size_t size )
{
void* p = NULL;
c_return_value_if_fail( array != NULL, NULL );
c_return_value_if_fail( size == array->element_size, NULL );
if ( array->size ) {
p = array->buffer;
}
return p;
}
#define c_array_front( array, type ) ( (type*)
(gc_array_front( (array), sizeof (type) )) )
\endcode
This can generate a constraint violation for c_array_front( ar, char )
if the original container array contains objects of type 'double', but
it cannot distinguish between invalid casting between 'int' and
'float' (if 'sizeof (int) == sizeof (float)').
It's a very special case though