0

I can use assert to make sure that the user of function passes correct values - e.g. that pointer to array is not NULL. But what if there is a case when function cannot possibly return anything sensible - e.g. it is popping a stack data structure - returning type in int and pointer to empty stack is passed?

Tom N
  • 51
  • 9
  • 1
    Pass an error address, like `strtol()` ... `int foo = strtol("42bar", 10, &err);` – pmg Jul 24 '22 at 18:40
  • 1
    Please _edit_ your question and post code that illustrates your issue. The `assert` has nothing to do with the return value [as it aborts the program on failure]. As a guess, you need an extra "error" arg: `int func(char *str,int *haserr) { int ret = (str == NULL); *haserr = ret; if (! ret) ret = ...; return ret; }` – Craig Estey Jul 24 '22 at 18:44
  • Why is the function returning an `int`? Can it be used to return an error code? – Reinstate Monica Jul 24 '22 at 18:45
  • 1
    In the stack case, you solve it by not using a poor architecture. There is a reason libs provide `empty()` , `top()` , and `pop()` artifacts, and `pop` either does nothing (at worst), or returns an error code (better) on under-pops; it does *not* return an actual datum value from the contained data. `pop` is a container manipulation operation; not a data retrieval operation. The onus is on the caller to check `empty` before accessing `top` or `pop`. – WhozCraig Jul 24 '22 at 18:51
  • Thank you very much for all the comments. I was working on Exercism problem so it is not real production code just academic example. That is why the function was just returning `int`. I was asking what is the general strategy to handle errors. – Tom N Jul 24 '22 at 20:15
  • 1
    You should certainly look at [Error handling in C code?](https://stackoverflow.com/q/385975/15168) IMO, the best technique is for the function to return a value indicating whether it succeeded or an error number if an error occurred. Returned values are handled via pointer arguments to the function. The POSIX `pthreads` library does this. Many systems use 0 for 'no error' and a negative number to indicate an error. Sometimes (e.g. Unix system calls such as `open()`), a positive value is a legitimate response. Other libraries (such as OpenSSL) use other conventions for the return values. – Jonathan Leffler Jul 24 '22 at 21:01

0 Answers0