I am implementing simple library for lists in C, and I have a problem with writing find
function.
I would like my function to accept any type of argument to find, both:
find(my_list, 3)
and find(my_list, my_int_var_to_find)
.
I already have information what is type of list's elements.
For now I've found couple of ways dealing with this:
different function with suffix for different types:
int findi(void* list, int i)
,int findd(void* list, double d)
- but I don't like this approach, it seems like redundancy for me and an API is confusing.using union:
typedef union { int i; double d; char c; ... } any_type;
but this way I force user to both know about
any_type
union, and to create it before invocation offind
. I would like to avoid that.using variadic function:
int find(void* list, ...)
. I like this approach. However, I am concerned about no restrictions on number of arguments. User is free to writeint x = find(list, 1, 2.0, 'c')
although I don't know what it should mean.
I have seen also answer to this question: C : send different structures for one function argument but it's irrelevant, because I want to accept non-pointer arguments.
What is the proper way of handling this function?