[cfe-dev] Nested _Generic selections in clang 3.0
Eli Friedman
eli.friedman at gmail.com
Mon Jan 23 11:53:18 PST 2012
On Mon, Jan 23, 2012 at 11:07 AM, Joel C. Salomon
<joelcsalomon at gmail.com> wrote:
> [First-time poster; if this is the wrong list would you please redirect me?]
>
> I'm attempting to use C11's _Generic selection expressions to enforce a
> kind of type consistency, and it's failing in an odd way.
>
> Motivation: In the revised IEEE 754 (2008, aka IEC 60559:2011) there is
> the function totalOrder(x, y) which is meaningful for each
> floating-point type, but meaningless for mixed types. I was wondering
> whether this was a candidate for _Generic selection: not simply for
> convenience, but for type safety as well.
>
> Consider a simpler case, the functions funcf() & funcd which I want to
> wrap in a macro func(x, y) so that
> * func(1.0f, 2.0f) calls funcf(),
> * func(1.0, 2.0) calls funcd(), and
> * func(1.0f, 2.0) & func(1.0, 2.0f) are invalid.
>
> My first effort looked like this:
>
> #include <stdio.h>
> void funcf(float x, float y) {
> printf("floats %f, %f\n", x, y);
> }
> void funcd(double x, double y) {
> printf("doubles %f, %f\n", x, y);
> }
> #define func(x, y) _Generic((x), \
> float: _Generic((y), float: funcf), \
> double: _Generic((y), double: funcd) ) (x, y)
> int main(void) {
> func(1.0f, 2.0f); // should (?) work
> // func(1.0f, 2.0); // shouldn't work
> // func(1.0, 2.0f); // shouldn't work
> func(1.0, 2.0); // should (?) work
> }
>
> I used LLVM Clang version 3.0, which complained about the lines which
> I'd intended to have work:
>
> gen.c:12:13: error: controlling expression type 'float' not compatible
> with any generic association type
> func(1.0f, 2.0f);
> ~~~~~~~~~~~^~~~~
> gen.c:10:20: note: expanded from:
> double: _Generic((y), double: funcd) ) (x, y)
> ^
> [And a similar error for the `func(1.0, 2.0)` line.]
>
> It seems that all "legs" of the selection expression are -- not
> "evaluated", but checked for type errors. Is this intentional?
Yes; expressions are type-checked in all contexts, and the standard
doesn't say anything that would contradict that for nested _Generic
expressions. Granted, the behavior described by the standard isn't
really ideal; it wouldn't be too hard to special-case parsing/semantic
analysis for nested _Generic expressions, but we would need a complete
proposal for the new rules.
-Eli
More information about the cfe-dev
mailing list