Many standard C and POSIX functions return -1
for error, and 0
on success, for example truncate
, fflush
, msync
, etc.
int ret = truncate("/some/file", 42);
Is it better practice to check for success with ret != -1
or ret == 0
, and why?
My Thoughts
It's my experience most people check for the error case (ret != -1
), as there is typically only one (consider functions that return NULL
or EOF
on error). However in hindsight, one could see these functions could benefit from returning errno
directly (where 0
is considered no error).
There is also the worry that a function returns something other than 0
or -1
, or that additional return values are later added. In these scenarios, it makes sense to test for the "tightest" range of values indicating success (ret == 0
).
Update0
It's an assumption of mine that people are aware that EOF
is typically defined as -1
.