function return value conventions

Programming, for all ages and all languages.
Post Reply
Adek336

function return value conventions

Post 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 :)
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Re:function return value conventions

Post 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.
B.E

Re:function return value conventions

Post 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.
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

Re:function return value conventions

Post by Neo »

C doesn't have a bool return type, does it?
You could enum and try though.
Only Human
User avatar
Colonel Kernel
Member
Member
Posts: 1437
Joined: Tue Oct 17, 2006 6:06 pm
Location: Vancouver, BC, Canada
Contact:

Re:function return value conventions

Post by Colonel Kernel »

In C99, bool is defined in stdbool.h.
Top three reasons why my OS project died:
  1. Too much overtime at work
  2. Got married
  3. My brain got stuck in an infinite loop while trying to design the memory manager
Don't let this happen to you!
Post Reply