Skip to content

Commit e719ba2

Browse files
sayoojkkarunnashif
authored andcommitted
include: zephyr: sys: simplify MIN_HEAP_FOREACH macro
Refactor the `MIN_HEAP_FOREACH` macro to use a cleaner for-loop style removing the need for a third `body` argument. Update the sample application with the new macro changes. Signed-off-by: Sayooj K Karun <[email protected]>
1 parent 964a832 commit e719ba2

File tree

3 files changed

+10
-14
lines changed

3 files changed

+10
-14
lines changed

.clang-format

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ ForEachMacros:
8282
- 'HTTP_SERVICE_FOREACH_RESOURCE'
8383
- 'I3C_BUS_FOR_EACH_I3CDEV'
8484
- 'I3C_BUS_FOR_EACH_I2CDEV'
85+
- 'MIN_HEAP_FOREACH'
8586
IfMacros:
8687
- 'CHECKIF'
8788
# Disabled for now, see bug https://github.com/zephyrproject-rtos/zephyr/issues/48520

include/zephyr/sys/min_heap.h

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -220,23 +220,18 @@ static inline void *min_heap_get_element(const struct min_heap *heap,
220220
*
221221
* @param heap Pointer to the heap.
222222
* @param node_var The loop variable used to reference each node.
223-
* @param body Code block to execute for each node.
224223
*
225224
* Example:
226225
* ```
227226
* void *node;
228-
* MIN_HEAP_FOREACH(&heap, node, {
227+
* MIN_HEAP_FOREACH(&heap, node) {
229228
* printk("Value: %d\n", node->value);
230-
* });
229+
* }
231230
* ```
232231
*/
233-
#define MIN_HEAP_FOREACH(heap, node_var, body) \
234-
do { for (size_t _i = 0; _i < (heap)->size && \
235-
(((node_var) = min_heap_get_element((heap), _i)) || true); \
236-
++_i) { \
237-
body; \
238-
} \
239-
} while (0)
232+
#define MIN_HEAP_FOREACH(heap, node_var) \
233+
for (size_t _i = 0; \
234+
_i < (heap)->size && (((node_var) = min_heap_get_element((heap), _i)) || true); ++_i)
240235

241236
/**
242237
* @}

samples/data_structures/min-heap/src/main.c

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,11 +57,11 @@ int main(void)
5757
}
5858

5959
printk("Heap elements by order of priority:\n");
60-
MIN_HEAP_FOREACH(&my_heap, elem, {
60+
MIN_HEAP_FOREACH(&my_heap, elem) {
6161
struct data *d = elem;
6262

6363
printk("key=%d value=%d\n", d->key, d->value);
64-
});
64+
}
6565

6666
printk("Top of heap: ");
6767
top = min_heap_peek(&my_heap);
@@ -77,11 +77,11 @@ int main(void)
7777
}
7878

7979
printk("Heap after removal:\n");
80-
MIN_HEAP_FOREACH(&my_heap, elem, {
80+
MIN_HEAP_FOREACH(&my_heap, elem) {
8181
struct data *d = elem;
8282

8383
printk("key=%d value=%d\n", d->key, d->value);
84-
});
84+
}
8585

8686
return 0;
8787
}

0 commit comments

Comments
 (0)