Page 1 of 1

function return value conventions

Posted: Fri May 13, 2005 8:59 am
by Adek336
Do you think it is better for a

Code: Select all

int makeTee();
function to return 0 on success and -1 on error, or
0 on success and 1 on error, or
1 on success and 0 on error or perhaps it should return an unsigned int?

I used to have functions with 1 and -1 retvals, but it seems the 0 and -1 method is used more often.

Cheers :)

Re:function return value conventions

Posted: Fri May 13, 2005 9:50 am
by Candy
the common method is to do the positive / -1 for functions that return valid values for normal use since you can easily pluck out -1. For most other functions (mainly predicate functions) the return values are 1 for a positive result and 0 for a negative one, for use in:

Code: Select all

if (allisok()) {
   // do something
} else {
   // complain
}
The if statement is implicitly true for all nonzero and false for zero. You can also use this with pointers, just an fyi:

Code: Select all

char *something = argv[2];
if (something) // something is not null
For returning values for most others, I use more elaborate return types, commonly a char *, int, double or something like that, and for the most exquisite functions I could use a pair<T1, T2> or a struct tailor-made for it. I also occasionally use haskell/prolog style argument passing, in which all functions are void in return type and can modify their arguments. I do this mainly for clarity in programs that process stuff like images sequentially, since you're not constantly reassigning the pointer to the newer stuff.

Re:function return value conventions

Posted: Fri May 13, 2005 11:24 pm
by B.E
if you uses a bool return type you do not have to wury about which value is true and wich value is false.

Re:function return value conventions

Posted: Mon May 16, 2005 6:37 am
by Neo
C doesn't have a bool return type, does it?
You could enum and try though.

Re:function return value conventions

Posted: Mon May 16, 2005 7:32 am
by Colonel Kernel
In C99, bool is defined in stdbool.h.