My program crashes because it reaches a stack.top() it shouldn’t reach, as the stack is empty.
I have an if which checks just that:
if(!st.empty());
//do stuff
(I have initialized
stack<int> st;
).
But although I can see in the debug that the stack is empty, it still goes in the if!
I even wrote this code:
if(st.size()>0);
cout<<st.size();
And it prints 0!
What is going on and how can I fix it? Thanks!
The semicolons after the if statements are the problem
BAD:
Properly rewritten:
Also, as @WhozCraig pointed out, the other statement has a semicolon too!
BAD:
Good:
ALWAYS!! use brackets with branches (if, switch), and loops (for, while, do-while)!!! It pays off big time! (Not to mention, a cute kitten dies each and every time such a block is written without brackets!) ALWAYS!!
For example this can kill a day in debugging:
BAD:
Good:
Beware (as @WhozCraig pointed out again) this does not automagically solve the problem of semicolon terminated branch and loop statements, as this is perfectly valid syntax:
Or
But in my opinion and experience (this is totally subjective!) – as I myself have fallen into this trap a couple of times – I experienced that when I have the curly bracket after the aforementioned statements, I didn’t ever make the mistake of typing a semicolon again. Adhering to this convention was a silver bullet – for me, and others could benefit from this too. Also, if there was a semicolon there, it would immediately catch my eye, just by looking, as it is an “uncommon pattern of characters”.