Skip to content
VecForeachPtrReverseIdx

VecForeachPtrReverseIdx

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 v->length - 1 and will go till 0

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 walking down from v->length - 1 to 0. 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)
                if (VecLen(vec) > 0) {
                    size_t total_len = 0;
                    VecForeachPtrReverseIdx(vec, str_ptr, idx) {
                        total_len += ZstrLen(*str_ptr) + idx;
                    }
                if (VecLen(vec) > 0) {
                    size_t total_len = 0;
                    VecForeachPtrReverseIdx(vec, str_ptr, idx) {
                        total_len += StrLen(str_ptr) + idx;
                    }
                if (VecLen(vec) > 0) {
                    int sum = 0;
                    VecForeachPtrReverseIdx(vec, item_ptr, idx) {
                        sum += *item_ptr + (int)idx;
                    }
    // Test VecForeachPtrReverseIdx macro
    bool test_vec_foreach_ptr_reverse_idx(void) {
        WriteFmt("Testing VecForeachPtrReverseIdx\n");
    
        // Create a vector of integers
    
        // Use VecForeachPtrReverseIdx to set each value to its index + 100
        VecForeachPtrReverseIdx(&vec, item_ptr, idx) {
            *item_ptr = idx + 100;
        }
    // Make idx go out of bounds in VecForeachPtrReverseIdx by modifying vector during iteration
    bool test_vec_foreach_ptr_reverse_idx_out_of_bounds_access(void) {
        WriteFmt("Testing VecForeachPtrReverseIdx where idx goes out of bounds (should crash)\n");
    
        typedef Vec(int) IntVec;
    
        // VecForeachPtrReverseIdx has explicit bounds checking: if ((idx) >= (v)->length) LOG_FATAL(...)
        VecForeachPtrReverseIdx(&vec, val_ptr, idx) {
            WriteFmt("Accessing idx {} (vec.length={}): {}\n", idx, VecLen(&vec), *val_ptr);
    /// TAGS: Foreach, Vec, Iteration, Loop, Reverse, Pointer
    ///
    #define VecForeachPtrReverse(v, var) VecForeachPtrReverseIdx((v), (var), UNPL(iter))
    
    ///
    /// TAGS: Str, Foreach, Iterate, Reverse
    ///
    #define StrForeachReversePtrIdx(str, chrptr, idx) VecForeachPtrReverseIdx((str), (chrptr), idx)
    
    ///
Last updated on