VecForeachIdx
- Macro
- August 22, 2025
Table of Contents
VecForeachIdx
VecForeachIdx
Description
Iterate over each element var
of given vector v
at each index idx
into the vector. The variables var
and idx
declared and defined by this macro. idx
will start from 0 and will go till v->length - 1
Parameters
Name | Direction | Description |
---|---|---|
v | in,out | Vector to iterate over. |
var | in | Name of variable to be used which’ll contain value at iterated index idx |
idx | in | Name of variable to be used for iterating over indices. |
Success
The body
is executed for each element of the vector v
from the beginning to the end.
Failure
If the vector v
is NULL or its length is zero, the loop body will not be executed. Any failures within the VecForeachIdx
macro (like invalid index access) will result in a fatal log message and program termination.
Usage example (Cross-references)
- In
Foreach.h:28
:
/// body : Body of this foreach loop.
///
#define StrForeachIdx(str, chr, idx, body) VecForeachIdx((str), (chr), idx, {body})
///
- In
Foreach.h:144
:
/// index access) will result in a fatal log message and program termination.
///
#define VecForeach(v, var, body) VecForeachIdx((v), (var), (____iter___), {body})
///
// Test VecForeachIdx macro
bool test_vec_foreach_idx(void) {
printf("Testing VecForeachIdx\n");
// Create a vector of integers
// Use VecForeachIdx to verify indices and values
bool result = true;
VecForeachIdx(&vec, item, idx, { result = result && (item == values[idx]); });
// Use VecForeachIdx to calculate weighted sum (value * index)
// Use VecForeachIdx to calculate weighted sum (value * index)
int weighted_sum = 0;
VecForeachIdx(&vec, item, idx, { weighted_sum += item * idx; });
// Check the weighted sum
// Deadend test: Make idx go out of bounds in VecForeachIdx by modifying vector during iteration
bool test_vec_foreach_idx_out_of_bounds_access(void) {
printf("Testing VecForeachIdx where idx goes out of bounds (should crash)\n");
typedef Vec(int) IntVec;
// VecForeachIdx has explicit bounds checking: if ((idx) >= (v)->length) LOG_FATAL(...)
VecForeachIdx(&vec, val, idx, {
printf("Accessing idx %zu (vec.length=%zu): %d\n", idx, vec.length, val);
// Deadend test: Make idx go out of bounds in basic VecForeachIdx by modifying vector during iteration
bool test_vec_foreach_idx_basic_out_of_bounds_access(void) {
printf("Testing basic VecForeachIdx where idx goes out of bounds (should crash)\n");
typedef Vec(int) IntVec;
// Basic VecForeachIdx now has explicit bounds checking: if ((idx) >= (v)->length) LOG_FATAL(...)
VecForeachIdx(&vec, val, idx, {
printf("Accessing idx %zu (vec.length=%zu): %d\n", idx, vec.length, val);