]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
basic/macros: add STRLEN() to get length of string literal as constant expression
authorThomas Haller <thaller@redhat.com>
Wed, 13 Dec 2017 07:17:07 +0000 (08:17 +0100)
committerThomas Haller <thaller@redhat.com>
Wed, 13 Dec 2017 10:12:07 +0000 (11:12 +0100)
While the compiler likely optimizes strlen(x) for string literals,
it is not a constant expression.

Hence,

  char buffer[strlen("OPTION_000") + 1];

declares a variable-length array. STRLEN() can be used instead
when a constant espression is needed.

It's not entirely identical to strlen(), as STRLEN("a\0") counts 2.
Also, it only works with string literals and the macro enforces
that the argument is a literal.

src/basic/macro.h

index 78679083e85e4f673a92aacc5cd9a10f6b290bbc..02d22de833f2be808d88928de5e20bf76970dc81 100644 (file)
@@ -144,6 +144,14 @@ static inline unsigned long ALIGN_POWER2(unsigned long u) {
                 !__builtin_types_compatible_p(typeof(x), typeof(&*(x))), \
                 sizeof(x)/sizeof((x)[0]),                                \
                 (void)0))
+
+/*
+ * STRLEN - return the length of a string literal, minus the trailing NUL byte.
+ *          Contrary to strlen(), this is a constant expression.
+ * @x: a string literal.
+ */
+#define STRLEN(x) (sizeof(""x"") - 1)
+
 /*
  * container_of - cast a member of a structure out to the containing structure
  * @ptr: the pointer to the member.