Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing the integer return value of a function to bool in C++

Consider the following C++ code snippet below:

...

if (false == func()) // Line #1
{
 ...
 ...
}

int func()
{
 ...
  {
     ...
     return false;
  }
 ...

 return true;
} 

In the code snippet above, the prototype of function func() indicates that it returns an integer. But inside the function func(), it returns either false or true.

Also in Line #1, the return value of function func() is checked against a boolean value.

I would like to know whether there is any problem with this type of usage. If there is some problem, recommend what rectifications needs to be done.

like image 958
nitin_cherian Avatar asked Dec 12 '25 21:12

nitin_cherian


1 Answers

There is no problem, any non-zero integer translates to true, and zero is false. Conversely, a bool can be converted to int, with true converting to 1 and false to 0.

You don't need to be so verbose when comparing boolean values though:

if (!func()) { .... }

Of course, if the function only returns true or false, as in your example, then it would make sense for it to return bool directly:

bool func();
like image 78
juanchopanza Avatar answered Dec 15 '25 12:12

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!