1

I'm currently writing a header file data_structures.h that contains several different data structures such as dynamic arrays and trees. My problem is, that I want to have a function like get_element() that can be both called with an instance of a dynamic array or a tree or any other data structure.

I know that there is no such thing as function overloading in C, but are there any best practice methods to get around this problem? Would it be best to just have another function name for each data structure, for example tree_get_element()?

int get_element(struct dynarray *a, int index); int get_element(struct tree *t, int index); 
1
  • There is _Generic keyword in C which allows for a limited form of overloading. Commented Oct 31, 2019 at 13:49

2 Answers 2

3

Would it be best to just have another function name for each data structure, for example tree_get_element()?

Yes, that is the way it's typically done in C.

But if you are using C11 compiler you can expand on this with generic expressions:

int dynarray_get_element(struct dynarray *a, int index); int tree_get_element(struct tree *t, int index); #define get_element(x, index) \ _Generic((x), \ struct dynarray *: dynarray_get_element,\ struct tree * : tree_get_element \ )((x), (index)) 
Sign up to request clarification or add additional context in comments.

Comments

1

There are two general approaches of dealing with this problem in C:

(1) Use a union and each type of pointer to user-class [you can try a different character for each union member to let the function know which call you made];

(2) Use a void * as the pointer to user-class [in this case, you need to use a char * or string type in order to specify the type name].

Now, for instance, (1) would be coded as:

union _dynarrtr_ { struct dynarray *a; struct tree *t; }; typedef union _dynarrtr_ UDynArrTree; /*UATChar is either 'a' or 't' (or whichever other union members there are)*/ int get_element(char UATChar, UDynArrTree *UATPtr, int index); 

And, (2) would be coded as follows:

/*Here, you can test 'typeStr' against the name of each type*/ int get_element(const char *typeStr, void *objPtr, int index); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.