Please help me to make a function stop/return an error without returning any value

I'm having an assignment to implement a stack class using singly linked list and here is my Pop function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

struct Node
{
	int val;
	Node* Next;
}

class stack
{
private:
	Node* top;
public:
	int Pop()
	{
	        if(top==NULL)
		      return ???; //what to do here???
	         Node* tmp=top;
	         int a=top->val;
	         top = top->Next;
	         delete tmp;
	         return a;
	}
}

As you can see, I don't know what the Pop function will do if the stack is empty, please help.
Thank you for your time and patience.
Last edited on
This looks like a job for exceptions:
http://www.cplusplus.com/doc/tutorial/exceptions/
You can return 1 or throw an exception
Thank you guys, I've spent some time to read the tutorial about exceptions (never heard of it before). Here's what I came up with, is it alright? I still feel that there's an error in the return part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <conio.h>
using namespace std;

struct Node
{
	int val;
	Node* Next;
}

class stack
{
private:
	Node* top;
public:
	int Pop()
	{
		try
		{
			Node* tmp=top;
			int a=top->val;
			top = top->Next;
			delete tmp;
			if(top==NULL)
				throw 'n';
		}
		catch(char c)
		{
			cout<<"ERROR";
		}
		return a;
	}
}
It shouldn't be an error to empty an stack

you should let the client to catch the exception.
You have four typical options; choose one, and document it.

Option one:
1
2
3
// invariant: !empty()
// calling Pop() on empty stack will result in undefined behaviour
int Pop() ;


Option two:
1
2
3
4
// invariant: !empty()
// invariant is asserted: assert( !empty() )
// NDEBUG: calling Pop() on empty stack will result in undefined behaviour
int Pop() ;


Option three:
1
2
3
// invariant: !empty()
// calling Pop() on empty stack throws an excdeption (std::out_of_range)
int Pop() ;


Option four:
1
2
3
4
// invariant: !empty()
// invariant is asserted: assert( !empty() )
// NDEBUG: calling Pop() throws an exception (std::out_of_range)
int Pop() ; 


My personal preference is for option two (provide assistance for debugging, but do not penalize a programmer who writes correct code because there could be others who may write incorrect code).
1
2
3
4
5
6
7
8
9
10
11
12
int Pop()
{
    assert( top != nullptr ) ; // #include <cassert>

    Node* tmp = top ;
    const int a = top->val ; // UB if top is null
    
    top = top->Next ;
    delete tmp ;
    
    return a ;
}
Topic archived. No new replies allowed.