0

When I'm writing a user define function, should I return 0 if the function is successful or a non null value?

I personally like to return 0 if my function is successful, but I always see error handling more like (!var) and less like (var != NULL). So would it be better to return some value like 1, as known as TRUE, even in a non-Boolean situation?

What does Stack Overflow suggest?

Reason why I'm asking is because I wrote a non-Boolean wrapper for WINAPI BOOL CreateProcessW and it threw my code off because I was returning 0 in the wrapper and before I was checking if TRUE.

3 Answers3

1

I find it easier to return non-zero on success because then you can say something like:

int result = foo()
if (!result) { .. }

which is much more clear on the intent. Often NULL is returned in exceptional or error cases, so returning NULL on success is counter-intuitive.

However, an even better solution would be to use enums for all the error codes and check against those and not use something like !result. This will let you handle the case when there are multiple error codes nicely as well.

Oleksi
  • 12,947
  • 4
  • 56
  • 80
  • 1
    I understand, but then how would you add a more precise error handling in the function you defined, if all you can return is `NULL` when there is an error? – user1450236 Jun 18 '12 at 20:05
  • @user1450236 you can't, which is why you can't always do this. You should only do this is there is only one error code (0). In other cases, you can return 0 on success. This way you write "cleaner" code whenever possible. Just make sure that you make it clear in the documentation what all the return codes may be. – Oleksi Jun 18 '12 at 20:09
0

I would say to just pick one and be consistent. If you are working with some other application in a significant way, try to be consistent with that code.

I like returning 0 on success and then using non-zero numbers for different error conditions. If you use 0 as your error, then you can only have one sort of returned error without getting into much more complicated error handling. But checking for !foo() can seem counter intuitive.

Justin
  • 2,322
  • 1
  • 16
  • 22
0

This is a really subjective question, but generally speaking I would suggest returning enum'd error codes and explicitly checking for the conditions you expect. This avoids situations such as the one you found yourself in.

Consistency is more important than any one scheme though.

Jon Cage
  • 36,366
  • 38
  • 137
  • 215