Skip to content

VecForeach

Description

Walk each element of v forward, binding var to the element value. Convenience wrapper around VecForeachIdx with an internally-managed index name. See VecForeachIdx for the full SUCCESS/FAILURE contract.

Usage example (Cross-references)

Usage examples (Cross-references)
                if (VecLen(vec) > 0) {
                    size_t total_len = 0;
                    VecForeach(vec, str) {
                        total_len += ZstrLen(str);
                    }
                if (VecLen(vec) > 0) {
                    size_t total_len = 0;
                    VecForeach(vec, str) {
                        total_len += StrLen(&str);
                    }
                if (VecLen(vec) > 0) {
                    int sum = 0;
                    VecForeach(vec, item) {
                        sum += item;
                    }
        JW_OBJ(json, {
            JW_OBJ_KV(json, "functions", {
                VecForeach(&symbols, symbol) {
                    Str source_key = StrInit(&alloc);
                    StrAppendFmt(&source_key, "{}", symbol.source_function_id);
        StrDeinit(&result->binary_name);
        StrDeinit(&result->sha256);
        VecForeach(&result->tags, tag) {
            StrDeinit(&tag);
        }
    
    bool test_vec_foreach(void) {
        WriteFmt("Testing VecForeach\n");
    
        // Create a vector of integers
        // Use VecForeach to sum the values
        int sum = 0;
        VecForeach(&vec, item) {
            sum += item;
        }
    
        // Use VecForeach to double each value
        VecForeach(&vec, item) {
            item *= 2;
        }
    // Make idx go out of bounds during VecForeach by modifying vector during iteration
    bool test_vec_foreach_out_of_bounds_access(void) {
        WriteFmt("Testing VecForeach where modification causes out of bounds access (should crash)\n");
    
        typedef Vec(int) IntVec;
        // VecForeach doesn't use an explicit index but we can still cause issues
        int iteration_count = 0;
        VecForeach(&vec, val) {
            WriteFmt("Iteration {} (vec.length={}): {}\n", iteration_count, VecLen(&vec), val);
    /// TAGS: Str, Foreach, Iterate
    ///
    #define StrForeach(str, chr) VecForeach((str), (chr))
    
    ///
            (void)___is_first___;                                                                                          \
            StrPushBackR(&(j), '[');                                                                                       \
            VecForeach(&(arr), item) {                                                                                     \
                if (___is_first___) {                                                                                      \
                    ___is_first___ = false;                                                                                \
Last updated on