Search code examples
c++booleanreturn-type

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


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?


Solution

  • If it's a genuine truth value, then you should use a bool as it makes it very clear to the caller what will be returned. When returning an int, it could be seen as a code/enum type value.

    Code should be as clear and explicit as possible whether it be function names, parameter names and types, as well as the types of the return codes. This provides more self-documenting code, code that is easier to maintain, and a lower probability that someone will misinterpret what you "meant".