Skip to content

StrForeachIdx

Description

Walk each character of str forward, binding chr to the character value at index idx. Both chr and idx are stamped by the macro and are visible inside the loop body. See VecForeachIdx for the full SUCCESS/FAILURE contract.

Usage example (Cross-references)

Usage examples (Cross-references)
                // byte). Two hex digits per byte, zero-padded.
                StrIntFormat config = {.base = 16, .uppercase = (fmt_info->flags & FMT_FLAG_CAPS) != 0};
                StrForeachIdx(s, c, i) {
                    if (i > 0) {
                        if (!StrPushBackR(o, ' ')) {
    // Test StrForeachIdx macro
    bool test_str_foreach_idx(void) {
        WriteFmt("Testing StrForeachIdx\n");
        DefaultAllocator alloc = DefaultAllocatorInit();
        // Build a new string by iterating through each character with its index
        Str result = StrInit(&alloc);
        StrForeachIdx(&s, chr, idx) {
            StrAppendFmt(&result, "{c}{}", chr, idx);
        }
    // Make idx go out of bounds in basic StrForeachIdx by modifying string during iteration
    bool test_str_foreach_idx_basic_out_of_bounds_access(void) {
        WriteFmt("Testing basic StrForeachIdx where idx goes out of bounds\n");
        DefaultAllocator alloc = DefaultAllocatorInit();
    
        // Basic StrForeachIdx (VecForeachIdx) now has explicit bounds checking: if ((idx) >= (v)->length) LOG_FATAL(...)
        StrForeachIdx(&s, chr, idx) {
            WriteFmt("Accessing idx {} (s.length={}): '{c}'\n", idx, StrLen(&s), chr);
Last updated on