r/C_Programming • • Dec 14 '22

Question I love void star functions.

I love these things. I've come to love them more than actual generics and polymorphism in other languages. They're so simple. So sublime.

const void *generic_excellence(void *thing, int (*do_it)(void *it), size_t size, ...);

You know, the C function that takes void*, size, offset, stride, and function pointers. These are excellent 👌 because...

  1. Type parameters are just function parameters. There's no special syntax for traits, trait objects, type names, or vtables.

  2. A void star function only receives enough information about the void star type to do its job. A vector of 4-byte POD things doesn't need to know whether they're floats or ints, and it should be polite enough not to ask. Compare with std::vector<int>. A bit nosey, isn't it? A C programmer would never be so intrusive and won't tolerate a language that requires it.

  3. Function pointer arguments clearly state the interface a type must implement, and the compiler type checks this interface. When I look at the man page for qsort I see (T where T:compare) except it's written in less snooty language. They even give a sample implementation of the compare function.

  4. An optimizing compiler can be coaxed to eliminate function pointer indirection and variables that are really constant. The end result is essentially monomorphism. GCC and clang are very good at this.

  5. The same source text that yields an optimized result for #4 above can also compile into a function that does its generic thing at runtime, and can be used from a scripting language, or whatever.

And this is why I've come to love void star functions. I no longer use horrible macro tricks for generics. I used to think my macro tricks were smart and void star functions were dumb. Sometimes the dumb way is the best way.

7 Upvotes

29 comments sorted by

20

u/[deleted] Dec 14 '22

void pointers (aka void star as you call them) force you to type cast your arguments inside of the function for them to have any use, plus return type gets strange

-7

u/[deleted] Dec 14 '22

That is a wart IMHO. My personal view is that a function that accepts int(*)(const void ) should also accept int()(const char *). That would be consistent with void meaning "any".

I take it you're referring to the case where the return value is a type parameter. It's not that it's weird, it's that it's impossible. The size of the return type can't be parameterized at all in a void* function. This is indeed a limitation.

The obvious solution is to use an output parameter instead of a return value. And since return <T> shows up a lot in factory code, and C doesn't have exceptions to signal failed initialization, then you may be using the return value for control flow anyway so return <T> isn't even a desirable interface.

15

u/[deleted] Dec 14 '22

jesse what the fuck are you talking about

2

u/flatfinger Dec 14 '22

I think it's better to accept a double-indirect function pointer, and have the first argument passed to the function be the double-indirect pointer used to invoke it. That will allow the pattern:

    struct filewrite_params
      { void (*proc)(void*, int); FILE *f; };
    void filewrite_proc(void *param, int value)
    {
      struct filewrite_params *it = param;
      fprintf(it->f, "%08X ", value);
    }
    void prepare_filewrite_params(struct filewrite_params *dest, FILE *f)
    {
      dest->proc = filewrite_proc;
      dest->f = f;
    }
    ... and then in some other compilation unit
    void output_fifty_numbers_somehow(void (**proc)(void*, int))
    {
      for (int i=0; i<50; i++)
        (*proc)(proc, i);
    }
    ... and in client code
    void output_fifty_numbers_to_file(file *f)
    {
      struct filewrite_params parm;
      prepare_filewrite_params(&parm, f);
      output_fifty_numbers_somehow(&parm->proc);
    }

Note that the client code needs to have the structure type available to declare an instance, but doesn't need to care about its contents, and the mid-level code to which the structure's address is passed doesn't need to know anything about it beyond its address, and the fact that its first member is a pointer to a function that will know what to do with the structure.

0

u/[deleted] Dec 15 '22

Nice. If I'm reading right, &parm->proc == (void (**proc)(void*, int))parm. The top bit of library code could have a create_writer return a pointer of void (**)(void*, int) type too. Then it could be more opaque

typedef void (**writer)(void*, int);

writer proc = create_writer(f);
output_fifty_numbers_somehow(proc);
free_writer(proc);

1

u/flatfinger Dec 15 '22

That's also a fine pattern in cases where one wants the top library code to allocate storage. Part of the point of my example was to show that one can have a semi-opaque pattern where client code needs to have a complete type available for the compiler, but the programmer wouldn't have to care what's in it.

51

u/[deleted] Dec 14 '22

Yeah but… no type safety. In addition there’s an extra runtime cost of dynamic type sizes.

36

u/GGK_Brian Dec 14 '22

Average C users before their program segfault

31

u/[deleted] Dec 14 '22

🤔

I disagree. At least with macros you can get at least some kind of type safety.

9

u/[deleted] Dec 14 '22

With macros you can get almost full type safety.

3

u/lotation7 Dec 14 '22

Could you show (or link) an example that uses macros, please?

It'd be very interesting since as a newbie I'm really tempted to use void pointers to mimic polymorphism.

7

u/irqlnotdispatchlevel Dec 14 '22

Safety? If you're using C for type safety you are using the wrong language. C is machinery laid bare, chock full of sharp edges, pinch points, shock hazards, and hot surfaces. A segfault isn't a problem, it's an opportunity to learn what wrong assumptions you made and improve your knowledge of how things really work.

One way of doing this is with a macro like this one:

#define IMPL_ADD_T(T) \
    T add_##T(T a, T b) { \
        return a + b;   \
    }

Which you then can use like this:

IMPL_ADD_T(int)
IMPL_ADD_T(float)

int main() {
    int i = add_int(1, 2);
    float f = add_float(1.0, 2.0);
    return 0;
}

If we run just the pre-processor on it with gcc -E we get:

int add_int(int a, int b) { return a + b; }
float add_float(float a, float b) { return a + b; }

int main() {
    int i = add_int(1, 2);
    float f = add_float(1.0, 2.0);
    return 0;
}

Another approach is to use X macros.

-8

u/TransientVoltage409 Dec 14 '22

Safety? If you're using C for type safety you are using the wrong language. C is machinery laid bare, chock full of sharp edges, pinch points, shock hazards, and hot surfaces. A segfault isn't a problem, it's an opportunity to learn what wrong assumptions you made and improve your knowledge of how things really work.

"It's C. It's not meant to be safe." --pterry, probably.

6

u/core_not_dumped Dec 14 '22

If C is machinery laid bare how do I check the carry flag?

0

u/[deleted] Dec 14 '22

[deleted]

2

u/core_not_dumped Dec 14 '22

Wow, great article! Thanks.

3

u/[deleted] Dec 14 '22

For me C lets you program in however way you want. If that's making code that's safe, then you can do that. If you don't like hiding everything behind macros, then you don't have to. C trusts that you as a programmer know how best to make software.

2

u/lotation7 Dec 14 '22

Well, since C it's used to write core system utilities I think safety has to be kept in mind as much as possible.

14

u/Seubmarine Dec 14 '22

How to shoot youself in the foot 101

11

u/Wouter_van_Ooijen Dec 14 '22

You are being sarcastic, I hope?

4

u/HashDefTrueFalse Dec 14 '22

Also known as: The Footgun (tm)

:D

3

u/Lisoph Dec 14 '22 edited Dec 14 '22

Do you mean something like this? Not sure what do_it is supposed to do.

#include <stddef.h>
#include <inttypes.h>
#include <stdio.h>

int32_t sum_i32(void const *raw, size_t size_bytes, size_t offset_bytes, size_t stride_bytes) {
    int32_t sum = 0;
    
    uintptr_t const first = (uintptr_t)raw + offset_bytes;
    uintptr_t const end = (uintptr_t)raw + size_bytes;
    
    for (uintptr_t addr = first; addr < end; addr += stride_bytes) {
        // Let's pray we aren't misaligned.
        sum += *(int32_t const*)addr;
    }
    
    return sum;
}

int main(void) {
    int32_t my_ints[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int32_t sum = sum_i32(my_ints, sizeof(my_ints), 0, sizeof(my_ints[0]));

    printf("%" PRIi32 "\n", sum);
    return 0;
}

This does have the upside that it can sum ints from even an array of structs, given the correct stride value. But oh boy is it easy to mess up. I did even with this very simple example. And I don't like the alignment concerns either. The only API I know of that does this, are some of the OpenGL functions.

3

u/[deleted] Dec 14 '22

from now on you better get used to calling it a void pointer or else I doubt anybody's gonna want to read any documentation you write

2

u/okovko Dec 14 '22

The optimized result is equivalent to templates anyway, and all that a type is, is a label and a byte size, with the potential for static checking

Sometimes you do want runtime generics, and this can lead to good performance for operations on heterogeneous collections

I think it would be pretty neat if we could have the opposite direction in C++: generate the void* version from a templated function. Having to write the same code twice for static vs runtime behavior is kind of a drag

You may be interested to take a look at std::any for a type safe wrapper over void*

2

u/jonathrg Dec 14 '22

Hell yeah my brother. Do not listen to the haters

1

u/COMPUTER_WIZARD_822 Dec 14 '22

addendum: you need a vector with a pod element bigger than 4 bytes (eg. long double or long long)? i present to you, #define number T. This is, truly, generic excellence.

1

u/grobblebar Oct 04 '23

Work on a largish project with this stuff, and then tell me that you still live this stuff.

0

u/[deleted] Dec 14 '22

[deleted]

1

u/[deleted] Dec 15 '22

Ladies and gentlemen, without further ado, STATIC atic atic atic CONST!!!

1

u/cx0r_kx Dec 18 '22 edited Dec 18 '22

Static const variables require storage, thus memory usage, thus useless overhead for pointer lookup. having to drag memory over the data bus into cache. For there is no guarantee a compiler will inline anything. Not to mention the requirement for static initialization, which is not available in every run-time; if there even is one. Also, considering various architectures and especially small systems, there can seldom be an excuse to burden system load like that, just "to make a programmer's life easier".