RE: [PATCH] linux/const.h: Explain how __is_constexpr() works

From: David Laight
Date: Thu Feb 03 2022 - 04:25:13 EST


From: Miguel Ojeda
> Sent: 02 February 2022 20:43
>
> On Mon, Jan 31, 2022 at 9:43 PM Kees Cook <keescook@xxxxxxxxxxxx> wrote:
> >
> > + * - The conditional operator ("... ? ... : ...") returns the type of the
> > + * operand that isn't a null pointer constant. This behavior is the
>
> Perhaps clarify that this happens only if it fits that case? ...
>
> > + * - If (x) is an integer constant expression, then the "* 0l" resolves it
> > + * into a null pointer constant, which forces the conditional operator
> > + * to return the type of the last operand: "(int *)".
> > + * - If (x) is not an integer constant expression, then the type of the
> > + * conditional operator is from the first operand: "(void *)".
>
> ... i.e. this one happens because it is specified as returning a
> pointer to void (one could read it as returning the type of the first
> operand).
>
> What about something like:
>
> - The behavior (including its return type) of the conditional
> operator ("... ? ... : ...") depends on the kind of expressions given
> for the second and third operands. This is the central mechanism of
> the macro.
> - If (x) is an integer constant expression, then the "* 0l" resolves
> it into a null pointer constant. When one operand is a null pointer
> constant and the other is a pointer, the conditional operator returns
> the type of the pointer operand; that is, "int *".
> - If (x) is not an integer constant expression, then that operand is
> a pointer to void (but not a null pointer constant). When one operand
> is a pointer to void and the other a pointer to an object type, the
> conditional operator returns a "void *" type.

Nick's quote from the C standard actually sums it up nicely:

The key here is that the conditional operator returns a different type
depending on whether one of the operands is a null pointer constant
(6.5.15.6):

[...] if one operand is a null pointer constant, the result has the
type of the other operand; otherwise, one operand is a pointer to void
or a qualified version of void, in which case the result type is a
pointer to an appropriately qualified version of void.

That followed by a reminder that "(void *)x is a null pointer constant if x
is a compile time integer constant expression" is enough.
All the rest is just TL;DR.

The '8' also just confuse things, they are not important at all.
So it can be:
#define __is_constexpr(x) \
(sizeof(*(0 ? ((void *)((long)(x) * 0)) : (int *)0)) == sizeof(int))

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
Registration No: 1397386 (Wales)