How to make generic function using void * in c?

后端 未结 7 2291
广开言路
广开言路 2020-12-13 07: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 functi

7条回答
  •  一整个雨季
    2020-12-13 08:29

    Sorry if this may come off as a non-answer to the broad question "How to make generic function using void * in c?".. but the problems you seem to have (incrementing a variable of an arbitrary type, and swapping 2 variables of unknown types) can be much easier done with macros than functions and pointers to void.

    Incrementing's simple enough:

    #define increment(x) ((x)++)
    

    For swapping, I'd do something like this:

    #define swap(x, y)                  \
    ({                                  \
            typeof(x) tmp = (x);        \
            (x) = (y);                  \
            (y) = tmp;                  \
    })
    

    ...which works for ints, doubles and char pointers (strings), based on my testing.

    Whilst the incrementing macro should be pretty safe, the swap macro relies on the typeof() operator, which is a GCC/clang extension, NOT part of standard C (tho if you only really ever compile with gcc or clang, this shouldn't be too much of a problem).

    I know that kind of dodged the original question; but hopefully it still solves your original problems.

提交回复
热议问题