From 18e107e09860332d01ea351f613266b192b678a8 Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Wed, 23 Nov 2022 11:03:56 +0100 Subject: [PATCH] std-aux: implement static-asserts via bitfields The implementation for static asserts with (sizeof(char[(cond) ? 1 : -1])) silently fails if the condition is not a compile time constant, because it results in a VLA which is evaluated at runtime. Well, for that reason we build with "-Wvla" to catch accidentally using a non-const expression in a static assert. But still, we can do better. Use instead bitfields to trigger the compiler error. This works only with static expressions and also without "-Wvla". https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/merge_requests/1468 --- src/libnm-std-aux/nm-std-aux.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/libnm-std-aux/nm-std-aux.h b/src/libnm-std-aux/nm-std-aux.h index 5fe94bf799..a8b18ef1b2 100644 --- a/src/libnm-std-aux/nm-std-aux.h +++ b/src/libnm-std-aux/nm-std-aux.h @@ -293,9 +293,8 @@ _nm_assert_fail_internal(const char *assertion, #define NM_STATIC_ASSERT(cond) static_assert(cond, "") #define NM_STATIC_ASSERT_EXPR_1(cond) \ - (sizeof(struct { char __static_assert_expr_1[(cond) ? 1 : -1]; }) == 1) -#define NM_STATIC_ASSERT_EXPR_VOID(cond) \ - ((void) (sizeof(struct { char __static_assert_expr_void[(cond) ? 1 : -1]; }) == 1)) + (!!sizeof(struct { unsigned __static_assert_expr_1 : ((cond) ? 2 : -1); })) +#define NM_STATIC_ASSERT_EXPR_VOID(cond) ((void) NM_STATIC_ASSERT_EXPR_1(cond)) /*****************************************************************************/