Should I use "int" or "bool" as a return value in C++?
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".
One thing that's not emphasized enough in the existing answers: Use bool certainly, but to get the most benefit, you simply must use good names for your bool variables and functions. I mention this because truthValue is a typical terrible name. Your bool names should always make the convention you are using obvious. Don't make other coders guess which way round the bool variable works. So;
Good names
bool okay;
bool error;
bool success;
bool IsWidget();
Bad names
bool truthValue;
bool status;
bool result;
bool Widget();
You see the difference ? Admittedly your truthValue is arguably better than status or result. But basically the bad names make for confusing code;
// Bad
bool result = Func();
if( result )
{
// Did Func() succeed or fail ? who knows
}
// Good
bool okay = Func();
if( okay )
{
// Func() succeeded
}
If you want to return a binary truth value then you should be using a boolean data type where available.
Compilers will optimise things if necessary, you should be writing your code as much as possible to be clear. That way, you or your successor will have no doubt five years down the track what was intended.
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).