Path: csiph.com!weretis.net!feeder8.news.weretis.net!eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.std.c Subject: Re: Allow a type as a first operand of `_Generic` Date: Sun, 29 Jan 2023 11:38:03 -0800 Organization: A noiseless patient Spider Lines: 55 Message-ID: <86tu09f7xg.fsf@linuxsc.com> References: <66c1e886-4e76-4343-b2e2-d1970f4959c2n@googlegroups.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader01.eternal-september.org; posting-host="8ce3893f3eb724e7abcf14dabf224dec"; logging-data="3051936"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+ipSqqSHvwyHsG9bbzyvxC/sADJxT79L8=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:/zXU25kHc6BK32jOJHrb+q32gZ4= sha1:aquEiZckP449h9wDLv3+wQxqIZk= Xref: csiph.com comp.std.c:6476 Tomasz Stanislawski 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.