Course contentsShow
← C
Lesson 1017 of 1,21914. Data Structures in CFree lesson

Dequeue operation logic

Dequeue operation logic

What you'll learn: How to safely remove the front element from a queue while maintaining the "First-In, First-Out" integrity of the data structure.

The "Exit Door" Logic

If you think of a Queue like a line of people waiting for coffee, the Dequeue operation represents the person at the very front finishing their order and leaving the shop. In C, this means we retrieve the data from the "front" index and then shift that front marker forward to the next person in line.

Crucially, we never remove someone from the middle or the back. We only ever serve the person who has been waiting the longest.

Two Steps to a Clean Exit

When coding a dequeue operation, your logic must handle two specific responsibilities:

  1. Check for Underflow: You cannot remove an item from an empty queue. If you try to access queue[front] when no data exists, your program will crash or behave unpredictably.
  2. Move the Front Marker: Once you grab the data, you increment your front pointer or index. In a simple array-based queue, this means front++.

Seeing it in Code

Here is how the logic looks when using a simple array-based structure. We use a structure that tracks the front and rear positions to know where the line starts and ends.

#include <stdio.h>

#define SIZE 5

struct Queue {
    int items[SIZE];
    int front;
    int rear;
};

int dequeue(struct Queue* q) {
    int removedValue;

    // 1. Check if the queue is empty
    if (q->front == -1 || q->front > q->rear) {
        printf("Queue Underflow! No one is in line.\n");
        return -1; 
    } else {
        // 2. Capture the data from the front
        removedValue = q->items[q->front];

        // 3. Increment front to "remove" the item
        q->front++;

        // Reset queue if it becomes empty after this removal
        if (q->front > q->rear) {
            q->front = q->rear = -1;
        }

        return removedValue;
    }
}

The "Virtual" Removal

Notice that in the code above, we don't actually erase the data in the array. We simply move the front index forward. By doing this, the old data becomes "invisible" to the rest of our queue functions. It’s like a person stepping away from the counter; even if they are still standing in the room, they are no longer part of the line.

Key takeaway

Dequeueing removes the element at the front index and increments that index to the next item, always checking first to ensure the queue isn't already empty.