aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--include/shared/linked_list.h10
-rw-r--r--tests/test_linked_list.c21
2 files changed, 26 insertions, 5 deletions
diff --git a/include/shared/linked_list.h b/include/shared/linked_list.h
index 17c2cdd..3f8e075 100644
--- a/include/shared/linked_list.h
+++ b/include/shared/linked_list.h
@@ -10,17 +10,17 @@
#define linked_list_front(type) linked_list_front_##type
#define linked_list_back(type) linked_list_back_##type
#define linked_list_length(type) linked_list_length_##type
-#define linked_list_length(type) linked_list_length_##type
#define LINKED_LIST_INIT \
{ \
.head = NULL \
}
-#define linked_list_foreach(ll, val) \
- for (typeof(ll.head) _cur_ = ll.head, typeof(_cur_->value) val; \
- _cur_ != NULL && ((val = _cur_->value) || 1); \
- _cur_ = _cur_->next)
+#define linked_list_foreach(ll, val) \
+ typeof(ll.head) _cur_ = ll.head; \
+ typeof(_cur_->value) val; \
+ if (_cur_) val = _cur_->value; \
+ for (; _cur_ != NULL; _cur_ = _cur_->next, val = _cur_ ? _cur_->value : val)
#define NO_ATTRIBUTE
diff --git a/tests/test_linked_list.c b/tests/test_linked_list.c
index 401091a..7ec96b5 100644
--- a/tests/test_linked_list.c
+++ b/tests/test_linked_list.c
@@ -39,3 +39,24 @@ TEST(linked_list, smell)
ASSERT_EQ(linked_list_front(int)(&ll), NULL);
return 0;
}
+
+TEST(linked_list, foreach)
+{
+ linked_list_t(int) ll = LINKED_LIST_INIT;
+ linked_list_push_front(int)(&ll, 3);
+ linked_list_push_front(int)(&ll, 2);
+ linked_list_push_front(int)(&ll, 1);
+
+ int i = 0;
+ int values[3];
+ linked_list_foreach(ll, val) {
+ values[i] = val;
+ ++ i;
+ }
+
+ ASSERT_EQ(values[0], 1);
+ ASSERT_EQ(values[1], 2);
+ ASSERT_EQ(values[2], 3);
+
+ return 0;
+}