Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.std.c > #6476

Re: Allow a type as a first operand of `_Generic`

From Tim Rentsch <tr.17687@z991.linuxsc.com>
Newsgroups comp.std.c
Subject Re: Allow a type as a first operand of `_Generic`
Date 2023-01-29 11:38 -0800
Organization A noiseless patient Spider
Message-ID <86tu09f7xg.fsf@linuxsc.com> (permalink)
References <66c1e886-4e76-4343-b2e2-d1970f4959c2n@googlegroups.com>

Show all headers | View raw


Tomasz Stanislawski <stanislawski.tomasz@googlemail.com> writes:

> 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?

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.

Back to comp.std.c | Previous | NextPrevious in thread | Find similar


Thread

Allow a type as a first operand of `_Generic` Tomasz Stanislawski <stanislawski.tomasz@googlemail.com> - 2023-01-25 04:43 -0800
  Re: Allow a type as a first operand of `_Generic` Tim Rentsch <tr.17687@z991.linuxsc.com> - 2023-01-29 11:38 -0800

csiph-web