Re: [PATCH] Use more gcc extensions in the Linux headers

From: Jan Engelhardt
Date: Sat Mar 10 2007 - 09:06:47 EST



On Mar 10 2007 16:19, Nigel Cunningham wrote:
>On Fri, 2007-03-09 at 23:03 -0500, Valdis.Kletnieks@xxxxxx wrote:
>> On Sat, 10 Mar 2007 09:57:32 +1100, Rusty Russell said:
>>
>> > +/* GCC is awesome. */
>> > #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) \
>> > + sizeof(typeof(int[1 - 2*!!__builtin_types_compatible_p(typeof(arr), \
>> > typeof(&arr[0]))]))*0)
>>
>> -/* GCC is awesome. */
>> +/* GCC leaves me speechless. */
>
>A speechless Rusty would be horrible. That said, it would be nice if the
>comment was something more like the normal Rusty pearl of wisdom. I
>understand the first part, but have no idea was + sizeof(typeof(int[....
>does...

IOCCC entry candidate.

Simple. !!__builtin_types_compatible_p, as it sounds, will return 1 if
both types are compatible. If they are, then '1-2*!!_builtin..' will
produce -1, then - surprisingly - sizeof(typeof(int[-1])) seems strange to
me and should throw the error.

If the types are not compatible, compat_p returns 0. !! will turn it into
0. 2* will turn it into 0. 1-0 is 1. sizeof(typeof(int[1])) is valid, and
*0 will compile it away.

So in case they _ARE_ compatible, we get the compile error, as far as I
can see it. There's a ! too much in the !!_builtin line. Now we know why
such patches are dangerous.

What's more, a test program does not even fail when the types are
incompatible. (Or it's also wrong):

#include <stdio.h>
struct foo {
int x, y, z;
};
struct bar {
const char *fol;
};
#define c(x, y) \
sizeof(typeof(int[1 - \
2*!!__builtin_types_compatible_p(typeof(x), typeof(y))]))
int main(void)
{
printf("%d\n", c(struct foo *, struct bar *));
printf("%d\n", c(int*, int*));
}

Both printf()s throw a compile time error.


Jan
--
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/