Skip to content
VecForeachPtrIdx

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

Name Direction Description
v in,out Vector to iterate over.
var in Name of variable to be used which’ll contain pointer to value at iterated index idx
idx in Name of variable to be used for iterating over indices.

Success

The loop body runs once for each element with var bound to VecPtrAt(v, idx) and idx advancing from 0 to v->length - 1. Use this form when the body needs to mutate the element through the pointer. The body is skipped when v is empty.

Failure

The macro itself does not fail. LOG_FATAL via ValidateVec(v) when v is uninitialised or corrupted.

Usage example (Cross-references)

Usage examples (Cross-references)
        }
    
        VecForeachPtrIdx(patterns, pattern, i) {
            if (BitVecStartsWith(bv, pattern)) {
                return i;
        }
    
        VecForeachPtrIdx(patterns, pattern, i) {
            if (BitVecEndsWith(bv, pattern)) {
                return i;
                if (VecLen(vec) > 0) {
                    size_t total_len = 0;
                    VecForeachPtrIdx(vec, str_ptr, idx) {
                        total_len += ZstrLen(*str_ptr) + idx;
                    }
                if (VecLen(vec) > 0) {
                    size_t total_len = 0;
                    VecForeachPtrIdx(vec, str_ptr, idx) {
                        total_len += StrLen(str_ptr) + idx;
                    }
                if (VecLen(vec) > 0) {
                    int sum = 0;
                    VecForeachPtrIdx(vec, item_ptr, idx) {
                        sum += *item_ptr + (int)idx;
                    }
    // Test VecForeachPtrIdx macro
    bool test_vec_foreach_ptr_idx(void) {
        WriteFmt("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;
        }
    // Make idx go out of bounds in VecForeachPtrIdx by modifying vector during iteration
    bool test_vec_foreach_ptr_idx_out_of_bounds_access(void) {
        WriteFmt("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) {
            WriteFmt("Accessing idx {} (vec.length={}): {}\n", idx, VecLen(&vec), *val_ptr);
    /// TAGS: Foreach, Vec, Iteration, Loop, Pointer
    ///
    #define VecForeachPtr(v, var) VecForeachPtrIdx((v), (var), UNPL(iter))
    
    ///
    /// TAGS: Str, Foreach, Iterate
    ///
    #define StrForeachPtrIdx(str, chrptr, idx) VecForeachPtrIdx((str), (chrptr), idx)
    
    ///
Last updated on