Alex Rivera | Logout

What should the 'pop()' method return when the stack is empty?

Asked 2011-09-12T15:16:33.727
22

Possible Duplicate:
C++ STL stack question: Why does pop() not throw an exception if the stack is empty?

When designing a stack in C++, what should the pop() method (or front() method) return when the stack is empty? Which of the following design is better?

  1. Throw an exception
  2. Undefined, but require the user calling isempty() method to check before calling pop()
  3. Return a bool code, while using an extra parameter (a reference) to pass the popped element
  4. Define an unique empty element

OK, I see that my question is not that clear, let me try to rewrite it:

There are some data structures which can be implemented based on linked list like stack, queue, and each of them has a methods returning the front element (or the tail).

I want to know, is there any principle guideline about designing such a method regarding the case when the data is empty.

And my definition of better is "easy to use correctly and hard to use incorrectly".

Edit
Report

1 Answer

2

I might suggest having both pop and trypop methods. pop would simply call trypop and throw and exception if it fails. My reasoning is that, for some uses of a stack, attempting to pop when the stack is empty is indicative of a program logic error that should not happen - either unbalanced push/pop, or mishandling of an earlier failure to push due to resource exhaustion. For other uses, failure to pop just means you're at the end of input. When using a programming model with exceptions, distinguishing these uses allows you to avoid cluttering the caller with performing the check for empty stack and throwing the exception.

answered 2011-09-12T16:12:19.377

Your Answer