StrForeachIdx
- Macro
- August 22, 2025
Table of Contents
StrForeachIdx
StrForeachIdx
Description
Iterate over each character chr
of the given Str str
at each index idx
. This macro is a direct alias for VecForeachIdx
specialized for Str. The variables chr
and idx
are declared and defined by the underlying macro.
Parameters
Name | Direction | Description |
---|---|---|
str | in,out | Str to iterate over. |
chr | in | Name of the variable to be used which will contain the character at the iterated index idx . The type of chr will likely be the character type used by the Str implementation (e.g., char ). |
idx | in | Name of the variable to be used for iterating over indices (i64). |
Usage example (Cross-references)
- In
Io.c:792
:
// Format each character as hex
StrIntFormat config = {.base = 16, .uppercase = (fmt_info->flags & FMT_FLAG_CAPS) != 0};
StrForeachIdx(s, c, i, {
if (i > 0) {
StrPushBack(o, ' ');
// Deadend test: 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) {
printf("Testing basic StrForeachIdx where idx goes out of bounds (should crash)\n");
Str s = StrInitFromZstr("Testing Basic"); // 13 characters
// Basic StrForeachIdx (VecForeachIdx) now has explicit bounds checking: if ((idx) >= (v)->length) LOG_FATAL(...)
StrForeachIdx(&s, chr, idx, {
printf("Accessing idx %zu (s.length=%zu): '%c'\n", idx, s.length, chr);
// Test StrForeachIdx macro
bool test_str_foreach_idx(void) {
printf("Testing StrForeachIdx\n");
Str s = StrInitFromZstr("Hello");
// Build a new string by iterating through each character with its index
Str result = StrInit();
StrForeachIdx(&s, chr, idx, { StrWriteFmt(&result, "{c}{}", chr, idx); });
// The result should be "H0e1l2l3o4"