Consider a ring buffer of size 4. After enqueuing 3 elements and dequeuing 1, what is the value returned by the next dequeue?
typedef struct {
int buffer[4];
int head;
int tail;
int max;
int count;
} RingBuffer;
void enqueue(RingBuffer *rb, int val) {
if (rb->count == rb->max) return; // full
rb->buffer[rb->head] = val;
rb->head = (rb->head + 1) % rb->max;
rb->count++;
}
int dequeue(RingBuffer *rb) {
if (rb->count == 0) return -1; // empty
int val = rb->buffer[rb->tail];
rb->tail = (rb->tail + 1) % rb->max;
rb->count--;
return val;
}
int main() {
RingBuffer rb = {.head=0, .tail=0, .max=4, .count=0};
enqueue(&rb, 10);
enqueue(&rb, 20);
enqueue(&rb, 30);
dequeue(&rb);
int result = dequeue(&rb);
return result;
}Remember that dequeue removes the oldest element first.
After enqueuing 10, 20, 30, the buffer has [10, 20, 30]. Dequeue removes 10 first. The next dequeue returns 20.
Which condition correctly checks if a ring buffer is full?
Count tracks how many elements are currently stored.
The buffer is full when the number of stored elements equals its maximum size.
What is the bug in this enqueue function for a ring buffer?
void enqueue(RingBuffer *rb, int val) { if (rb->count == rb->max) return; rb->buffer[rb->head] = val; rb->head = (rb->head + 1) % rb->max; rb->count++; }
Check the condition that prevents adding when full.
The condition allows enqueue when count equals max, causing overflow. It should be == to prevent adding when full.
Which option correctly initializes a ring buffer struct in C?
Use designated initializers with dot notation in C.
Option D uses correct C99 designated initializer syntax. Others are invalid syntax.
Given a ring buffer of max size 5, starting empty, after these operations:
- enqueue 1
- enqueue 2
- dequeue
- enqueue 3
- enqueue 4
- enqueue 5
- dequeue
- enqueue 6
How many items are currently stored in the buffer?
Track count carefully after each enqueue and dequeue.
Operations add or remove items, final count is 4.