I have an incr
function to increment the value by 1
I want to make it generic,because I don't want to make different functions for the same functionality.
Suppose I want to increment int
,float
,char
by 1
void incr(void *vp)
{
(*vp)++;
}
But the problem I know is Dereferencing a void pointer is undefined behaviour
. Sometimes It may give error :Invalid use of void expression
.
My main
funciton is :
int main()
{
int i=5;
float f=5.6f;
char c='a';
incr(&i);
incr(&f);
incr(&c);
return 0;
}
The problem is how to solve this ? Is there a way to solve it in C
only
or
will I have to define incr()
for each datatypes ? if yes, then what's the use of void *
Same problem with the swap()
and sort()
.I want to swap and sort all kinds of data types with same function.
You can use the type-generic facilities (C11 standard). If you intend to use more advanced math functions (more advanced than the
++
operator), you can go to<tgmath.h>
, which is type-generic definitions of the functions in<math.h>
and<complex.h>
.You can also use the
_Generic
keyword to define a type-generic function as a macro. Below an example:You can find more information on the language standard and more soffisticated examples in this post from Rob's programming blog.
As for the
* void
, swap and sort questions, better refer to Jerry Coffin's answer.