Reputation: 1824
I am fairly new to programming languages and wonder if it is possible to pass an argument without specific type to a function. For instance I have the following piece of code that defines a funcion add
that will take a block of memory, check it if is filled via another function, and then adds an element to the list related to that block of memory.
This element can be an int, a float or a char. So I would like to write:
add(arrs1,20); //or also
add(arrs2,'b'); //or also
add(arrs3, 4.5);
Where arrs# are defined by struct arrs arrs#
, and they refer to arrays of either floats, ints or chars but not mixed. How could I accomplish this?
int add(arrs list, NEW_ELEMENT){//adds NEW_ELEMENT at the end of an arrs
int check_if_resize;
check_if_resize=resize(list, list->size + 1);
list->ptr[list->used++] = NEW_ELEMENT;
return check_if_resize;
}
I appreciate your help.
Upvotes: 0
Views: 968
Reputation: 384
You can pass pretty much anything as a void * in a function that will add this content to a linked list by the use of memcpy (or even safe memmove). As long as you have a pointer to the next node of your list, you don't have to worry about the type of the stored data. Just be sure not to dereference a void *, but rather to cast it and use this casted variable (as a char if you want to work on this data byte by byte for instance)
Upvotes: 1
Reputation: 40814
C does, by design, not allow a single function to accept more than a single type for each argument. There are various ways to do something equivalent in C, though:
First and foremost, you can just write multiple different functions that do the same, but on different types. For instance, instead of add
you could have three functions named add_int
, add_char
and add_float
. I would recommend doing this in most cases, as it is by far the easiest and least error-prone.
Secondly, you might have noticed how printf
can print both strings and numbers? So-called variadic functions, like printf
, can take different types of arguments, but in the case of printf
, you must still specify the type of arguments you want in the format string.
Finally, you can use void
pointers if you need to work with the memory an object occupies, regardless of its type. Functions like memcpy
and memset
do this, for instance to copy the contents of one object directly to another. This is a bit harder to manage properly, as it is easy to make mistakes and end up corrupting memory, but its still doable (and sometimes even the best option).
But if you're a beginner in C, as you state you are, the first option is probably the easiest, especially when dealing with only a few different data types (in this case, three).
Upvotes: 5