How to make generic function using void * in c?

2020-02-08 01:48发布

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 Conly

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.

7条回答
太酷不给撩
2楼-- · 2020-02-08 02:46

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:

#include <stdio.h>

#define add1(x) _Generic((x), int: ++(x), float: ++(x), char: ++(x), default: ++(x))

int main(){
  int i = 0;
  float f = 0;
  char c = 0;

  add1(i);
  add1(f);
  add1(c);

  printf("i = %d\tf = %g\tc = %d", i, f, c);
}

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.

查看更多
登录 后发表回答