Re: [PATCH v3 3/5] stddef: Add const_cast()
From: David Laight
Date: Wed Nov 11 2026 - 05:37:29 EST
On Tue, 10 Nov 2026 16:33:40 +0100
Alejandro Colomar <alx@xxxxxxxxxx> wrote:
> This macro serves to cast const away without risking unwanted
> conversions due to mistakes in the cast.
>
> It's similar to C++'s const_cast(), but it is more restrictive: it can
> only cast away 'const', and not arbitrary qualifiers.
>
> Signed-off-by: Alejandro Colomar <alx@xxxxxxxxxx>
> ---
> include/linux/stddef.h | 12 ++++++++++++
> 1 file changed, 12 insertions(+)
>
> diff --git a/include/linux/stddef.h b/include/linux/stddef.h
> index e1851c50c89b..d79a81406b78 100644
> --- a/include/linux/stddef.h
> +++ b/include/linux/stddef.h
> @@ -194,4 +194,16 @@ enum {
> #define TRAILING_OVERLAP(TYPE, NAME, FAM, MEMBERS) \
> __TRAILING_OVERLAP(TYPE, NAME, FAM, /* no attrs */, MEMBERS)
>
> +/**
> + * const_cast() - Drop const in the left-most derivation of a pointer
> + *
> + * @T: Type for the cast.
> + * @p: Pointer to be casted.
> + *
> + * If @p is of type const @T, then it is casted to @T.
> + * Otherwise, @p is returned without any casts.
> + * This avoids mistakes that change anything other than 'const' in a cast.
> + */
> +#define const_cast(T, p) _Generic(p, const T: (T) (p), default: (p))
Should it be de_const_cast(), or just de_const().
It is a shame you need to specify the type, but why not:
_Generic(p, T: p, const T: (T)(p))
so that you get a compile time error from the _Generic() if the type
is wrong.
David
> +
> #endif