Skip to content
VecForeachPtrInRangeIdx

VecForeachPtrInRangeIdx

Description

Iterate over elements in a specific range of the given vector v at each index idx (as pointers). The variables var and idx are declared and defined by this macro.

idx will start from start and will go till end - 1

Parameters

Name Direction Description
v in,out Vector to iterate over.
var in Name of pointer variable to be used which’ll point to value at iterated index idx.
idx in Name of variable to be used for iterating over indices.
start in Starting index (inclusive).
end in Ending index (exclusive).

Success

The loop body runs once for each element with var bound to VecPtrAt(v, idx) and idx advancing from start to min(end, v->length) - 1. Use this form when the body mutates elements in place.

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 (start < end) {
                        size_t total_len = 0;
                        VecForeachPtrInRangeIdx(vec, str_ptr, idx, start, end) {
                            total_len += ZstrLen(*str_ptr) + idx;
                        }
                    if (start < end) {
                        size_t total_len = 0;
                        VecForeachPtrInRangeIdx(vec, str_ptr, idx, start, end) {
                            total_len += StrLen(str_ptr) + idx;
                        }
                    if (start < end) {
                        int sum = 0;
                        VecForeachPtrInRangeIdx(vec, item_ptr, idx, start, end) {
                            sum += *item_ptr + (int)idx;
                        }
    // Make idx go out of bounds in VecForeachPtrInRangeIdx by modifying vector during iteration
    bool test_vec_foreach_ptr_in_range_idx_out_of_bounds_access(void) {
        WriteFmt("Testing VecForeachPtrInRangeIdx where idx goes out of bounds (should crash)\n");
    
        typedef Vec(int) IntVec;
        // Use VecForeachPtrInRangeIdx with a fixed range that becomes invalid when we modify the vector
        size original_length = VecLen(&vec); // Capture this as 9
        VecForeachPtrInRangeIdx(&vec, val_ptr, idx, 0, original_length) {
            WriteFmt("Accessing idx {} (vec.length={}): {}\n", idx, VecLen(&vec), *val_ptr);
    /// TAGS: Foreach, Vec, Iteration, Loop, Range, Pointer
    ///
    #define VecForeachPtrInRange(v, var, start, end) VecForeachPtrInRangeIdx((v), (var), UNPL(iter), (start), (end))
    
    #endif // MISRA_STD_CONTAINER_VEC_FOREACH_H
    ///
    #define StrForeachPtrInRangeIdx(str, chrptr, idx, start, end)                                                          \
        VecForeachPtrInRangeIdx((str), (chrptr), idx, (start), (end))
    
    ///
Last updated on