[PATCH 2/7] stddef: implement scoped_var for use in iterators

Ahmad Fatoum
2026-04-13T10:11:51Z

Our various iterator macros depend on a variable being declared
beforehand, which can be error prone as the value after the last
iteration completed may not be stable or even invoke undefined behavior
on access.

To allow restricting lifetime to only the iteration, implement
scoped_var, a macro for scoping a variable definitions to the statement
following it. The implementation is inspired by Linux __scoped_class.

Signed-off-by: Ahmad Fatoum <a.fatoum@barebox.org>
---
include/linux/stddef.h | 29 +++++++++++++++++++++++++++++
1 file changed, 29 insertions(+)

diff --git a/include/linux/stddef.h b/include/linux/stddef.h
index 88ff6f1733d2..e5e0421fe558 100644
--- a/include/linux/stddef.h
+++ b/include/linux/stddef.h
@@ -139,4 +139,33 @@ typedef unsigned short wchar_t;
#define DECLARE_FLEX_ARRAY(TYPE, NAME) \
__DECLARE_FLEX_ARRAY(TYPE, NAME)

+#define __scoped_var(decl, _label) \
+ for (decl; ; ({ goto _label; })) \
+ if (0) { \
+_label: \
+ break; \
+ } else
+
+/**
+ * scoped_var - declare a variable scoped to the following statement
+ * @type: the full type (e.g. ``struct foo *`` or ``int``)
+ * @name: the variable name to declare
+ *
+ * Declares @name as @type, initialized to 0, whose scope is limited
+ * to the immediately following statement. Works with both pointer and
+ * scalar types. Intended for use with existing loop macros to add scoped
+ * iterator variables without duplicating the loop body.
+ *
+ * Example with a list iterator:
+ *
+ * .. code-block:: c
+ *
+ * scoped_var(struct foo *p)
+ * list_for_each_entry(p, &head, member) {
+ * // use p
+ * }
+ * // p is out of scope here
+ */
+#define scoped_var(decl) __scoped_var(decl, __UNIQUE_ID(label))
+
#endif
--
2.47.3