Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use "int" or "bool" as a return value in C++?

Tags:

c++

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 either a boolean variable, or an int variable, as the return type?

bool Foo()
{
  ...
  ...
  return truthValue;
}

int Foo()
{
  ...
  ...
  return truthValue;
}

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

thanks,

nmr

like image 668
ihtkwot Avatar asked Jan 20 '10 03:01

ihtkwot


People also ask

Should I use bool or int?

If you choose a bool (boolean) type, it is clear there are only two acceptable values: true or false . If you use an int (integer) type, it is no longer clear that the intent of that variable can only be 1 or 0 or whatever values you chose to mean true and false .

Is bool a return type in C?

The return type is bool, which means that every return statement has to provide a bool expression.

Can bool function return integer?

In C++ the boolean literals true and false are converted to values of the return type of the first function. The literal true is converted to the integer value 1 and the literal false is converted to the integer value 0 .

What is the difference between int and bool?

Using bool conveys intent, a bool value is unambiguously true or false , while an integer value can take on many more states. This ambiguity could contribute to errors when code is maintained, for example.


2 Answers

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".

like image 77
RC. Avatar answered Oct 07 '22 07:10

RC.


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.

like image 29
paxdiablo Avatar answered Oct 07 '22 08:10

paxdiablo