Lesson 32 of 50
cQueues (FIFO) Using Circular Buffers
12 mins
Course progress64%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 32 of 50
c12 mins
Keep these ideas in mind as you work through the lesson.
A queue follows first‑in‑first‑out. A circular buffer efficiently implements a fixed‑size queue without moving elements.
#define CAP 5
int q[CAP];
int front = 0, rear = 0, size = 0;
int enqueue(int x) {
if (size == CAP) return -1; // full
q[rear] = x;
rear = (rear + 1) % CAP;
++size;
return 0;
}
int dequeue(int *out) {
if (size == 0) return -1; // empty
*out = q[front];
front = (front + 1) % CAP;
--size;
return 0;
}