Hey guys! I was trying to make Stack's push and pop functions. My push() is working fine but my pop() is giving me a headache. It doesn't delete the very last element entered in to the stack, where that might be!
#include <iostream>
#include <conio.h>
usingnamespace std;
class stack
{
private:
enum { MAX = 10 };
int st [MAX];
int top;
public:
stack() : top(-1)
{}
void push(int x)
{ st[++top] = x; }
void pop(int y)
{ y = st[top];
top--; }
void output()
{
for(int x = 0; x<MAX; x++)
{
cout<<st[x]<<" ";
}
}
};
int main()
{
stack s1;
int y;
s1.push(78);
s1.push(67);
s1.pop(y);
s1.pop(y);
s1.push(45);
s1.pop(y);
s1.push(23);
s1.pop(y);
s1.output();
_getch();
return 0;
}
According to my code here, pop() should have deleted 23 too! But it doesn't! And I can't make a teeny bit a sense of it! Please help! Thanks in advance!
And oh! Is there a way, the PC recognizes the variable contains garbage value and doesn't display it?! Just wondering!
y inside the pop function is a copy of the variable that you passed to the function in main. Making changes to the copy will not affect the original object.
You can make it work by passing the argument by reference. You only need change line 15.
void pop(int& y)
Another way is to return the popped value as a function return value. Personally I prefer this way.