VecForeachPtrIdx

Table of Contents

VecForeachPtrIdx

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

NameDirectionDescription
vin,outVector to iterate over.
varinName of variable to be used which’ll contain value at iterated index idx
idxinName of variable to be used for iterating over indices.

Usage example (Cross-references)

    /// body        : Body of this foreach loop.
    ///
    #define StrForeachPtrIdx(str, chrptr, idx, body) VecForeachPtrIdx((str), (chrptr), idx, {body})
    
    ///
    ///           index access) will result in a fatal log message and program termination.
    ///
    #define VecForeachPtr(v, var, body) VecForeachPtrIdx((v), (var), (____iter___), {body})
    
    ///
    }
    
    VecForeachPtrIdx(patterns, pattern, i, {
    if (BitVecStartsWith(bv, pattern)) {
    return i;
    }
    
    VecForeachPtrIdx(patterns, pattern, i, {
    if (BitVecEndsWith(bv, pattern)) {
    return i;
    // Test VecForeachPtrIdx macro
    bool test_vec_foreach_ptr_idx(void) {
    printf("Testing VecForeachPtrIdx\n");
    
    // Create a vector of integers
    
    // Use VecForeachPtrIdx to set each value to its index
    VecForeachPtrIdx(&vec, item_ptr, idx, { *item_ptr = idx; });
    
    // Check that the values in the vector are set to their indices
    // Deadend test: Make idx go out of bounds in VecForeachPtrIdx by modifying vector during iteration
    bool test_vec_foreach_ptr_idx_out_of_bounds_access(void) {
    printf("Testing VecForeachPtrIdx where idx goes out of bounds (should crash)\n");
    
    typedef Vec(int) IntVec;
    
    // VecForeachPtrIdx has explicit bounds checking: if ((idx) >= (v)->length) LOG_FATAL(...)
    VecForeachPtrIdx(&vec, val_ptr, idx, {
    printf("Accessing idx %zu (vec.length=%zu): %d\n", idx, vec.length, *val_ptr);

Share :