Range Over Channels in C

Our example demonstrates iterating over values received from a channel. In C, we don’t have built-in channels, so we’ll simulate this behavior using a queue implemented with an array.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define QUEUE_SIZE 2

typedef struct {
    char* items[QUEUE_SIZE];
    int front;
    int rear;
    int itemCount;
} Queue;

void initQueue(Queue* q) {
    q->front = 0;
    q->rear = -1;
    q->itemCount = 0;
}

void enqueue(Queue* q, const char* item) {
    if (q->itemCount < QUEUE_SIZE) {
        q->rear = (q->rear + 1) % QUEUE_SIZE;
        q->items[q->rear] = strdup(item);
        q->itemCount++;
    }
}

char* dequeue(Queue* q) {
    if (q->itemCount > 0) {
        char* item = q->items[q->front];
        q->front = (q->front + 1) % QUEUE_SIZE;
        q->itemCount--;
        return item;
    }
    return NULL;
}

int main() {
    Queue queue;
    initQueue(&queue);

    // We'll iterate over 2 values in the queue.
    enqueue(&queue, "one");
    enqueue(&queue, "two");

    // This loop iterates over each element as it's
    // received from the queue. The loop terminates after
    // receiving the 2 elements.
    while (queue.itemCount > 0) {
        char* elem = dequeue(&queue);
        printf("%s\n", elem);
        free(elem);
    }

    return 0;
}

To run the program, compile it and then execute:

$ gcc range_over_queue.c -o range_over_queue
$ ./range_over_queue
one
two

This example demonstrates how to iterate over elements in a queue, which is similar to ranging over a channel in other languages. We’ve implemented a simple queue using an array and provided enqueue and dequeue operations to mimic channel behavior.

The main difference here is that C doesn’t have built-in support for channels or a range-based for loop. Instead, we use a while loop to iterate over the queue elements until it’s empty. This approach achieves a similar result to ranging over a channel, allowing us to process each element in the queue sequentially.

Remember that in C, we need to manage memory manually. In this example, we use strdup to allocate memory for each string in the queue, and we free this memory after we’ve used each element.