[cfe-dev] Nested _Generic selections in clang 3.0
Joel C. Salomon
joelcsalomon at gmail.com
Mon Jan 23 11:07:18 PST 2012
[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?
On comp.lang.c I asked if this was correct behavior. Clark Nelson,
author of <http://bit.ly/c11-n1404> & <http://bit.ly/c11-n1441> (whom I
CC'd) put it best:
> I'm afraid that, when I made the proposal, I hadn't thought about
> this issue, and the proposal (and the text that's in the standard)
> simply doesn't make clear whether an application like yours is
> supposed to be valid or not. In my opinion, your application seems
> reasonable -- but of course that's just my opinion.
--Joel Salomon
More information about the cfe-dev
mailing list