Thank you guys, I've spent some time to read the tutorial about exceptions (never heard of it before). Here's what I came up with, is it alright? I still feel that there's an error in the return part
You have four typical options; choose one, and document it.
Option one:
1 2 3
// invariant: !empty()
// calling Pop() on empty stack will result in undefined behaviour
int Pop() ;
Option two:
1 2 3 4
// invariant: !empty()
// invariant is asserted: assert( !empty() )
// NDEBUG: calling Pop() on empty stack will result in undefined behaviour
int Pop() ;
Option three:
1 2 3
// invariant: !empty()
// calling Pop() on empty stack throws an excdeption (std::out_of_range)
int Pop() ;
Option four:
1 2 3 4
// invariant: !empty()
// invariant is asserted: assert( !empty() )
// NDEBUG: calling Pop() throws an exception (std::out_of_range)
int Pop() ;
My personal preference is for option two (provide assistance for debugging, but do not penalize a programmer who writes correct code because there could be others who may write incorrect code).
1 2 3 4 5 6 7 8 9 10 11 12
int Pop()
{
assert( top != nullptr ) ; // #include <cassert>
Node* tmp = top ;
constint a = top->val ; // UB if top is null
top = top->Next ;
delete tmp ;
return a ;
}