### Question for a bool function

Hello,

I've looked over the net for a function to break a vector into three parts with equal sum and I found the following. However, I can't combine in my mind the type of the function (bool) and the value it returns. I mean, given it is a bool function it suppose to return a true or false, so I'd expect to see "return true" or "return false". Instead it returns the counter and yet during runtime it indeed returns a 0 or 1. So my question is, how is possible to write "return variable" and not true/false, and the function to return a true or false? What do I miss here?

Thank you!

 ``12345678910111213141516171819`` `````` bool part3(vector & arr) { int summ = accumulate(arr.begin(), arr.end(), 0); int part = 0; int count = 0; if (summ % 3 == 0) { for (int x : arr) { part += x; if (part == (summ / 3)) { count++; part = 0; } } } return count >= 3; // <-------------- this ``````
Last edited on
count >= 3 is a condition which returns a type bool - either true if count is >= 3 or false if count < 3.

In general, in c/c++ a non-zero value is treated as true and a zero value is treated as false.

The expression "count >= 3" evaluates to a boolean. If count == 0, the expression is false. If count == 5, the expression is true. The evaluated expression is returned. The function is not returning the counter.

Boolean values can be seen as integers with values of 0 (false) and non-0 (true). An actual bool true is '1'. Since your function returns a bool, the returned value will either be 0 or 1.

All integers can be implicitly converted to a bool. If the int value is == 0, the bool is false. Otherwise the bool is true. This works for floats, doubles and pointers, too.

Excellent! Thank you guys!
Topic archived. No new replies allowed.