So my book has this example program meant to show how to use stacks and queues. It uses a stack to determine if a group of characters in a queue is parenthetically correct(every "(" has a matching ")" in the right place, etc). Here's the function:
template <class T>
bool testQueue( Queue<T> &q )
{
const string balTokenTableOpen ( "{[(" );
const string balTokenTableClose( "}])" );
const string quoteTokens( "'\"" );
Stack<T> s;
char c, cl;
string test; //What's the point of this variable?
int pos;
bool esc = false;
bool OK = true;
while ( !( q.isEmpty() ) && OK )
{
q.dequeue( c );
test = c; // assigned to c here
if ( esc ) // ignore the character after the escape character
{
esc = false;
continue;
}
if ( c == '\\' )
{
esc = true;
}
elseif ( balTokenTableOpen.find( test ) != string::npos ) //Why can't you just use c instead of test?
{
s.push( c );
}
elseif ( ( pos = balTokenTableClose.find( test ) ) != string::npos ) //Used again here.
{
if ( s.isEmpty() )
OK = false;
else
{
s.pop( cl );
if ( balTokenTableOpen.at( pos ) != cl )
OK = false;
}
}
elseif ( quoteTokens.find( test ) != string::npos ) // And again.
{
char temp;
s.getTop( temp ); // No need to check catch an error here because
if ( s.isEmpty() || temp != c ) // we will catch empty stack here. Notice how short-circuit evaluation is used.
s.push( c );
else
{
s.pop();
}
}
}
if ( esc || !( s.isEmpty() ) )
OK = false;
return OK;
}
I'm wondering why the program declares the string "test" and uses it when it seems like it could just use "c" instead. The book claims that there is a reason, but doesn't specify it. I tried to figure it out, and I even replaced all uses of "test" with "c", ran the program, and it worked exactly the same with no errors. I see absolutely no point in using test. Is there something I'm missing?