StrForeachPtrInRangeIdx

Table of Contents

StrForeachPtrInRangeIdx

Description

Iterate over characters in a specific range of the given Str str at each index idx (as pointers). This macro is a direct alias for VecForeachPtrInRangeIdx specialized for Str. The variables chrptr and idx are declared and defined by the underlying macro.

Parameters

NameDirectionDescription
strin,outStr to iterate over.
chrptrinName of pointer variable to be used which’ll point to character at iterated index idx.
idxinName of variable to be used for iterating over indices.
startinStarting index (inclusive).
endinEnding index (exclusive).

Success

The body is executed for each character of the Str str from the start index to the end-1 index, with chrptr pointing to each character.

Failure

If the Str str is NULL, its length is zero, or the range is invalid, the loop body will not be executed. Any access to an invalid index will result in a fatal log message and program termination.

Usage example (Cross-references)

    // Deadend test: Make idx go out of bounds in StrForeachPtrInRangeIdx by modifying string during iteration
    bool test_str_foreach_ptr_in_range_idx_out_of_bounds_access(void) {
    printf("Testing StrForeachPtrInRangeIdx where idx goes out of bounds (should crash)\n");
    
    Str s = StrInitFromZstr("Comprehensive Testing Framework"); // 32 characters
    // Use StrForeachPtrInRangeIdx with a fixed range that becomes invalid when we modify the string
    size original_length = s.length; // Capture this as 32
    StrForeachPtrInRangeIdx(&s, chr_ptr, idx, 0, original_length, {
    printf("Accessing idx %zu (s.length=%zu): '%c'\n", idx, s.length, *chr_ptr);
    // Test StrForeachPtrInRangeIdx macro
    bool test_str_foreach_ptr_in_range_idx(void) {
    printf("Testing StrForeachPtrInRangeIdx\n");
    
    Str s = StrInitFromZstr("Hello World");
    // Build a new string by iterating through a range of character pointers with indices
    Str result = StrInit();
    StrForeachPtrInRangeIdx(&s, chrptr, idx, 6, 11, {
    // Append the character and its index to the result string
    StrWriteFmt(&result, "{c}{}", *chrptr, idx);

Share :