Alex Rivera | Logout

Should I return int or bool as a "truth value"?

Asked 2010-01-20T03:18:26.227
16

If I have a function that performs some procedure and then needs to return the truth value of something, is there a compelling reason to use int or bool as the return type?

bool Foo() {
  // ...
}

// vs.

int Foo() {
  // ...
}

Is there an appreciable difference between these two functions? What are some potential pitfalls and advantages to both of them?

Edit
Report

3 Answers

6

Use bool -- it more clearly conveys the semantic meaning of your code. If another developer reads your code and sees a return type of bool, he immediately understands that it returns a truth value. If instead he sees that it returns an int, he has to dig a little further and spend more time figuring out the interface to the function (e.g. reading documentation or reading the code), which slows him down.

The only reason to use int is if you need to interface with legacy code and/or conform to a particular interface (e.g. your function gets its address taken and passed to a third-party library that expects a function of a certain prototype).

answered 2010-01-20T03:21:56.283
2

There are a couple of considerations. If Foo is intended to be callable from C, you can't return a bool because C doesn't know what a bool is.

int can also return values other than true or false. This is either a good thing or a bad thing depending on whether or not Foo can have other meaningful return values. If it can however, it may make more sense for Foo to return an enum value instead of an int.

If you don't have compatibility with C as a requirement, I would suggest the bool.

answered 2010-01-20T03:24:06.263
0

If truthValue is a bool return bool.

This prevents a type coersion (no biggie).

Another reason is it is conventional to return an int to report status where 0 is successful and non-zero number represents an error condition. So the following would be unintutive from the callers perspective:

int process()
{
   bool success = false
   if (the process was successful)
      success = trrue;
   return success;
};

Conventionally, it should be either

bool process()
{
   bool success = false
   if (the process was successful)
      success = true;
   return success;
}

so main is:

int main()
{   return process() ? EXIT_SUCCESS : EXIT_FAILURE; }

or

int process()
{
  int result = EXIT_FAILURE
  if (the process was successful)
    result = EXIT_SUCCESS
  return result;
};

so main is:

int main()
{ return process(); }
answered 2010-01-20T03:40:26.523

Your Answer