Re: [PATCH v4 1/2] compiler.h: add const_true()
From: Linus Torvalds
Date: Sun Nov 17 2024 - 13:00:42 EST
On Sun, 17 Nov 2024 at 09:42, David Laight <David.Laight@xxxxxxxxxx> wrote:
>
> #define const_true(x) __if_constexpr(x, x, 0)
No, let's not do this "double expansion" thing again.
If we actually want to make things smarter, the trick to use is to
know that only a constant _zero_ turns into a void pointer (aka NULL).
IOW, something like this:
/*
* iff 'x' is a non-zero constant integer expression,
* then '!(x)' will be a zero constant integer expression,
* and casting that to 'void *' will result in a NULL
* pointer. Otherwise casting it to 'void *' will be just
* a regular 'void *'.
*
* The type of '0 ? NULL : (char *)' is 'char *'
* The type of '0 ? (void *) : (char *) is 'void *'
*/
#define const_true(x) \
_Generic(0 ? (void *)((long)!(x)) : (char *)0, char *: 1, void *: 0)
should work, and doesn't do any double expansion of complex arguments.
Linus