Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What return value should you use for a failed function call in C? [duplicate]

Tags:

c

Possible Duplicate:
Error handling in C code

Let's say you have a function:

int MightWork(){
  // if it works
  return x;

  // if it fails
  return y;

}

what should x and y be?

because I have another function:

if (MightWork){
  // do stuff #1
}else{
  // do stuff #2
}

I know for this particular example, using a return value of 1 will take the second code block to "do stuff # 1" and using a return value of 0 will take the second code block to "do stuff #2"

My question is what is preferred style in C to do this? Does a return value of 0 for a function indicate success and any other value indicates failure? Or vice versa? Or values under 0?

I'd like to make sure I'm writing my C code with the current style. Thanks!

like image 728
oxuser Avatar asked Nov 14 '11 01:11

oxuser


1 Answers

For non-pointer success/fail:

  • 0 => success
  • -1 => fail

For pointer functions:

  • NULL => fail
  • everything else => success
like image 186
moshbear Avatar answered Sep 19 '22 16:09

moshbear