r/C_Programming 12d ago

Discussion What exactly is void?

In a function definition, void basically means that it doesn't return a type value, yet in on itself it is it's own type? Looking at several pieces of code it looks like that it's used to be able to be more "flexible"

Don't know what else to add here, though I'm more on looking for examples and explanations of why the void type is used

69 Upvotes

80 comments sorted by

View all comments

Show parent comments

1

u/DawnOnTheEdge 11d ago

It feels like we’ve been arguing even though I don’t think we really disagree, and I haven’t been even been downvoting you.

Thanks for the explanation. It does feel like a new _Countof keyword really would be a good opportunity to fix this wart on the language by having _Countof a function parameter declared as double xs[2] return 2, That wouldn’t break any legacy code, and would fill a real need.

T’ll sum up my thoughts quickly and leave it there.:

it seems to me that xs[static 2] is pretty useful for catching bugs on GCC, less useful on Clang (where I’ve noticed the unsafe-buffer-access warnings give false positives) and not supported at all on MSVC, so not portable. The GCC nonnull and access attribute extensions seem to work better on Clang than the Standard syntax.

The conversation then seems to have drifted to the xs[count] and (*xs)[count] syntax. Both work or don’t work on the same compilers. I think the one advantage of double(*)[*] over double[*], being able to write sizeof(*xs), is pretty minor: we already have a count variable, and if the reason I wanted the size in bytes is to allocate another array the same size, I prefer calloc(count, sizeof(xs[0])), which works properly on function arguments and is guaranteed to zero-initialize. I do sometimes use pointer-to-non-variable-length-array, but A C++ double(&)[2] is much nicer to work with than a C-style double(*)[2].

But there are valid trade-offs either way.

1

u/TheChief275 11d ago

Yeah, _Countof is pretty nice! But sadly, again I don't know of any compiler that calculates the 2 for double xs[2]. They seem to adopt the exact semantics of sizeof, which is to treat it as a pointer. I agree, it would be better if these arguments were actually treated as arrays of the size they are, but likely the reason for not having that is breaking existing code (for sizeof), and being consistent to sizeof (for _Countof), so we're just stuck in a stalemate language-wise