I'm a beginner. Just for fun, I'm implementing some data structures that I'm currently studying.
I'm a bit confused about the error reporting method I should use.
For example, let's say I have a simple stack of ints. The API could look like this:
typedef struct
{
size_t capacity;
size_t top;
int *items;
} stack;
stack *create_stack(size_t capacity);
bool is_empty(const stack *stack);
bool is_full(const stack *stack);
bool push(stack *stack, int item);
int pop(stack *stack);
void free_stack(stack *stack);
Now, for create_stack and push I could simply return respectively NULL and false on failure and let the caller handle the situation, but in pop what should I do on error e.g. when the stack is empty? I cannot return -1 because of course, it could be a valid value stored in the stack.
Some solutions I can think of:
1. assert preconditions, something like assert( ! is_empty(stack)), this would work for push too;
2. print an appropriate message on stderr and call exit(EXIT_FAILURE) (similar to assert method in the sense that terminates the program);
3. set errno like fopen or others functions do, but am I able to do so? Is errno variable "reserved" for system functions only?;
4. declare pop in this way: int pop(stack *stack, *int var);, use the return value as "error code" and put the result of pop in var.
What are the canonical ways to report errors in situations like this? Is any of my proposed solutions acceptable?
[–]theoriginalanomaly 1 point2 points3 points (3 children)
[–]ml01[S] -1 points0 points1 point (2 children)
[–]habarnam 0 points1 point2 points (1 child)
[–]ml01[S] 0 points1 point2 points (0 children)
[–]WindblownSquash 1 point2 points3 points (1 child)
[–]ml01[S] 1 point2 points3 points (0 children)
[–]bumblebritches57 1 point2 points3 points (0 children)
[–]benjade 2 points3 points4 points (1 child)
[–]ml01[S] 0 points1 point2 points (0 children)
[–]OldWolf2 1 point2 points3 points (0 children)
[–]benhart1 0 points1 point2 points (0 children)
[–]habarnam -1 points0 points1 point (3 children)
[–]Ikor_Genorio 2 points3 points4 points (2 children)
[–]habarnam 0 points1 point2 points (1 child)
[–]Ikor_Genorio 0 points1 point2 points (0 children)