Skip to contentSkip to conversation

Use _Generic() to implement __is_constexpr()

PATCH New David Laight 1 participant 1 message Nov 10, 2023 Sparse checker

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 Use _Generic() to implement __is_constexpr()

This is somewhat more obvious than relying on sizeof(void) being 1. It is also portable to any c11 compiler.

Change the constants to 0 - they have no bearing on the result and just confuse the reader.

It relies on the type of (expr ? NULL : (type *)any) being 'type *' but that of (expr ? (void *)x : (type *)any) being 'void *'.

---

I'm not 100% sure all of 'tools' sets -std=gnu99 or -std=c11 to get _Generic() supported.

This version will also be usable in 'nolibc' where sizeof(void) is an error.

 include/linux/compiler.h       | 2 +-
 tools/include/linux/compiler.h | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
include/linux/compiler.h +1 -1
index bb1339c7057b..2e11e216fd69 100644
@@ -233,7 +233,7 @@ static inline void *offset_to_ptr(const int *off)
  * Glory to Martin Uecker <[email protected]>
  */
 #define __is_constexpr(x) \
-	(sizeof(int) == sizeof(*(8 ? ((void *)((long)(x) * 0l)) : (int *)8)))
+	_Generic(0 ? (void *)((long)(x) * 0) : (char *)0, char *: 1, void *: 0)
 
 /*
  * Whether 'type' is a signed type or an unsigned type. Supports scalar types,
tools/include/linux/compiler.h +1 -1
index 7b65566f3e42..6e7f05196414 100644
@@ -69,7 +69,7 @@
  * Glory to Martin Uecker <[email protected]>
  */
 #define __is_constexpr(x) \
-	(sizeof(int) == sizeof(*(8 ? ((void *)((long)(x) * 0l)) : (int *)8)))
+	_Generic(0 ? (void *)((long)(x) * 0) : (char *)0, char *: 1, void *: 0)
 
 #ifdef __ANDROID__
 /*
Signature · 5 lines
2.17.1

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