0

What should I return when trying to dequeue an empty queue?

My textbook tells be to return a 'key' that signals an error.

I tried :

Element queueEmpty()
{
    Element elem = {'!'};
    printf("Queue is empty");
    return elem;
}

but figured that it's not a good design since '!' is not a unique representation of an error.

(Assuming that any char data can be a valid input)

My full code for Queue ADT & dequeue function :

typedef struct
{
    char data;
} Element;

typedef struct Node *nodePtr;
typedef struct Node
{
    Element elem;
    nodePtr next;
} Node;

nodePtr front[MAX_QUEUES];
nodePtr rear[MAX_QUEUES];





Element dequeue(int i)
{
    Element elem;
    nodePtr temp = front[i];
    if(!front[i])
    {
        return queueEmpty();
    }
    elem = temp->elem;
    front[i] = temp->next;
    free(temp);
    return elem;
}

FYI : My textbook is : "Fundamentals of Data Structures in C" by Horowitz, Sahni, Anderson-Freed

1
  • If ...:'!' is not a unique representation of an error.", then perhaps you know something that is. How would we know what that would be, when we didn't even know ! was unacceptable until you said so? Commented Apr 11, 2016 at 6:03

2 Answers 2

1

Why not returning a integer and using an pointer as additional output like this:

int dequeue (int i, Element *elem)
{
nodePtr temp = front[i];
if(!front[i])
{
    return -1; // Error parttern
}
*elem = temp->elem;
front[i] = temp->next;
free(temp);
return elem;
}

Calling:

Element elem;
if(dequeue(i,&elem) == -1)
{
 // Queue was empty
}
else
{
 // do what you want to do
}
Sign up to request clarification or add additional context in comments.

Comments

0

There are two things you can try:

  1. Return an invalid Element. In this case the user needs to check the returned element is valid or not.
  2. Throw an exception, when the user is trying to call dequeue operation on empty queue.

Personally I'll recommend the second way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.