C++: Using a Stack to Verify if Parentheses are Balanced (Logic error) <p>I have a simple stack I created with basic initialize, show, push, pop, top, etc. functions. I need a function to verify whether or not a string has matching parentheses. I think I'm pretty close, but I have a problem with the following: <strong>if (s.size == 0 &amp;&amp; c == ')')</strong> in the middle of my balanced function.</p> <p>This condition should be met by string "s1" with the parenthesis just prior to the division sign, but it is not...It is still returning true.</p> <p>Thanks for looking.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;stdlib.h&gt; using namespace std; struct Stack{ static const unsigned MAX_SIZE = 5; char data[ MAX_SIZE ]; unsigned size; }; void initialize( Stack &amp; stack ); void show( const Stack &amp; stack ); unsigned getSize( const Stack &amp; stack ); void push( Stack &amp; stack, char c ); char pop( Stack &amp; stack ); char top( const Stack &amp; stack ); bool die( const string &amp; msg ); bool balanced (const string &amp; expr); int main(){ string s1 = "X*((4+(3-2)/(Y+X))+(Z-8))) / ((A+(B-2))"; string s2 = "())"; string s3 = "(()"; cout &lt;&lt; balanced(s1) &lt;&lt; endl; cout &lt;&lt; balanced(s2) &lt;&lt; endl; cout &lt;&lt; balanced(s3) &lt;&lt; endl; } void initialize( Stack &amp; stack ){ stack.size = 0; } void show( const Stack &amp; stack ){ cout &lt;&lt;"[" &lt;&lt; stack.size &lt;&lt;"]:"; for( unsigned i = 0; i &lt; stack.size; i++ ) cout &lt;&lt;stack.data[i]; cout &lt;&lt;endl; } // show unsigned getSize( const Stack &amp; stack ) {return stack.size;} void push( Stack &amp; stack, char c ){ if( stack.size == Stack::MAX_SIZE ) die( "push: overflow" ); stack.data[stack.size++] = c; } // push char pop( Stack &amp; stack ){ if( stack.size == 0 ) die( "pop: underflow" ); return stack.data[--stack.size]; } // pop char top( const Stack &amp; stack ){ if( stack.size == 0 ) die( "top: underflow" ); return stack.data[stack.size-1]; } // top bool die( const string &amp; msg ){ cerr &lt;&lt;endl &lt;&lt;"Fatal error: " &lt;&lt; msg &lt;&lt;endl; exit( EXIT_FAILURE ); } bool balanced (const string &amp; expr){ Stack s; initialize(s); for (unsigned i = 0; i &lt; expr.size(); i++){ char c = expr[i]; if (c == '(') { if( expr.size() == Stack::MAX_SIZE ) { die( "push: overflow" ); } push(s, c); } if (s.size == 0 &amp;&amp; c == ')') { return false; } else if (c == ')'){ pop(s); } if (s.size == 0){ return true; } else return false; } } </code></pre>