I was wondering whether there are any pre-agreed values, coming from the old days of C language, that reflect tha function execution threw exception/terminated abruptly/failed for any reason? Is this value 0, or -1 or is it completely up to you and no standards exist?
Asked
Active
Viewed 67 times
1
-
For some questions like `find the index of a character in a string` 0 is a legal value so `-1` indicates failures. – parapura rajkumar Dec 18 '11 at 18:16
2 Answers
5
Functions that return pointers usually return NULL
to indicate failure (e.g. malloc
).
Most POSIX functions return 0
on success, and non-zero on failure. If they need to return a non-zero value as part of normal operation, they often return a negative value on failure.
But this is all just convention.

Oliver Charlesworth
- 267,707
- 33
- 569
- 680
0
One common convention is to return an invalid value, whatever it is. For instance, functions returning lengths may return -1 on failure.
General purpose error codes tend to be 0 or NULL
to mimick malloc's behavior. POSIX, on the other hand, uses the inverse convention.
Be sure to get accustomed to errno
for more "advanced" error checking. Many standard library routines put an error code there to be checked on failure.

Alexandre C.
- 55,948
- 11
- 128
- 197