|
|
Let's assume that silly_routine()
is called
in the middle of a very large program,
and the client programmer does not want the
program to abort on an overflow error.
Having looked at the recovery procedures
for the two Objections,
the programmer decides to ignore the overflow Objection.
This means that the stack will not change after it reaches its full state; that
is, if 14 integers are read in, only the first 10 will be on the stack.
The problem is that pnum
will continue to
grow in the first loop even when nothing is being added to the stack.
In the above
case, pnum
will equal 14 when the while loop ends.
Since the program pops pnum
items from the stack
in the next while loop,
it will try to pop an empty stack on the 11th iteration.
This will cause the Stack::underflow
Objection
to be raised.
Therefore, the client programmer
decides to ignore the Stack::underflow
Objection as well, which will cause pop()
to return
a MAXINT when the stack is empty.
This means adding two lines to the code, and
changing the print to be conditional upon the value returned from
pop()
:
void silly_routine()
{
Stack::overflow.ignore(); // added line
Stack::underflow.ignore(); // added line
int i;
while( cin >> i ) {
st.push(i);
pnum++;
}
while(pnum > 0) {
if( (i = st.pop()) != MAXINT) { // added line
cout << i << "\\n";
}
pnum--;
}
}
Now, the program will not abort; and only the values which actually get put on the stack will be output.