1

I'm trying to implement a queue and for dequeue I've purposely done with an int procedure. What would be possible drawbacks for using an int?

int dequeue(queue *q) {
    int res = 0; // list not empty

    node *tmp = NULL;

    if (q->first != res) {
        tmp = q->first->next; // store the value after the first one 
        free(q->first);
        q->first = tmp;
    }
    
    free(tmp);
    return res;
}

I was thinking if it could it be that maybe that position already has 0 and that we cannot be sure that it's "not empty"?

But then it's never safe to use an int to determine whether it is empty or not?

1
  • A value of -1 could mean empty? Commented Feb 17 at 2:08

1 Answer 1

2

Some issues:

  1. You're defining res as an int.

  2. But, res is actually more useful as a node *.

  3. And, you were comparing it to a node * (i.e. if (q->first != res)).

  4. The function, as written, doesn't do the dequeue properly. Caller should do the free after having used it.

Make some changes:

  1. Change function return type to node * (e.g. node *dequeue(queue *))

  2. Change int res = 0; to node *res = q->first;

  3. Change if (q->first != res) to if (res != NULL)

Then, caller can do (e.g.):

node *cur = dequeue(&myqueue);
if (cur != NULL)
    do_something_with_node(cur);

Here is a reworked version:

node *
dequeue(queue *q)
{
    // point to node to dequeue [if any]
    node *res = q->first;

    // remove node from queue
    if (res != NULL)
        q->first = res->next;

    // caller must free this node when done ...

    return res;
}

void
user_of_queue(queue *q)
{

    while (1) {
        // dequeue an element
        node *node = dequeue(q);

        // queue is empty
        if (node == NULL)
            break;

        do_something_with_node(node);

        free(node);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I was "requested" to post an answer. See stackoverflow.com/staging-ground/…
And a worthy answer it is, especially the point about returning a node-pointer to the dequeued or deleted node so that it can be freed by the caller. I think you hit the tone just right. int can convey information by return, just not as fully useful information. With many function returns, int is a fantastic choice as it provides simple 3-state returns (< 0, == 0 or > 0) for quick testing. However, in the case of any data structure, a pointer to the node provides immediate access to the node found (for whatever purpose).
Perhaps it is not a good idea to expose node. It's an implementation detail. Users don't need to know about it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.