Discussion:
Allow a type as a first operand of `_Generic`
(too old to reply)
Tomasz Stanislawski
2023-01-25 12:43:32 UTC
Permalink
I've noticed that some new C11 projects often use a pattern:

```
#define some_macro(type) _Generic((type){0}, ...)
```
to dispatch expression depending on some type type`.

The `(type){0}` is a compound literal used to create a dummy value of type `type` that is only used to dispatch expressions in generic selection. This approach is cumbersome and difficult to read.

I think that it would be beneficial to allow both values and types be operands of `_Generic` in a similar way as for `sizeof` operator.

This would let simplify the macro to:
```
#define some_macro(type) _Generic(type, ...)
```

It looks like a relatively trivial change to C grammar and wording of the C standard that will not break any existing code. Or am I missing something?
Tim Rentsch
2023-01-29 19:38:03 UTC
Permalink
Post by Tomasz Stanislawski
```
#define some_macro(type) _Generic((type){0}, ...)
```
to dispatch expression depending on some type type`.
The `(type){0}` is a compound literal used to create a dummy value of
type `type` that is only used to dispatch expressions in generic
selection. This approach is cumbersome and difficult to read.
I think that it would be beneficial to allow both values and types be
operands of `_Generic` in a similar way as for `sizeof` operator.
```
#define some_macro(type) _Generic(type, ...)
```
It looks like a relatively trivial change to C grammar and wording of
the C standard that will not break any existing code. Or am I
missing something?
Some reactions...

I don't know what the use cases for such a pattern might be. What
sorts of things are these? I expect that in most cases they are
rather unusual constructions, but can you give some representative
examples?

Given that uses normally occur in a macro definition, is it so bad
that the macro body makes use of this idiom, which is both fairly
easy to understand and pretty short?

If it is thought important to convey the idiomatic usage, that can
easily be done with an auxiliary macro:

#define VALUE_OF_TYPE( T ) ((T){0})

which can then be used in the invocation of _Generic. (I might or
might not use such a macro myself, depending on circumstances; I
don't see the choice as being compelling either way.)

Generally speaking, code that depends on types directly is more
brittle than code that depends on the type of an expression.
Allowing _Generic to take a type argument seems to encourage a
more dubious programming practice.

So, without more information, I'm inclined to think extending the
rules for _Generic to allow a type instead of an expression, even if
such a change is feasible and not very burdensome, is not really a
good idea. Just because something can be done doesn't mean it
should be done.

Loading...