Why does function return bool when it is defined as an int?
Well, why it returns is because that's the way you wrote it, but I guess you're asking, how/why does this work?
And the answer is that for convenience, C is perfectly willing to perform a number of implicit conversions between values of different types. This is usually a good thing, and once you get used to it, you'll appreciate it.
Let's look at the lines you were probably puzzled about.
int hum2()
{
return true;
}
If function hum2 is declared as returning int, how can you return this Boolean value from it? Well, deep down, a Boolean is just a number, generally either 0 or 1. So there's no problem returning that number as an int. The compiler typically doesn't even warn you. This is partly because, once upon a time, C did not even have a separate Boolean type, and everybody used int (or some other integer type) to store their 1/0 true/false values.
The situation here is kind of like declaring a function
double one()
{
return 1;
}
Here function one is declared as returning type double, yet we return an int. How does this work? Well, again, the compiler is perfectly willing to perform an implicit conversion.
The other line you were probably puzzled about was this one:
printf("%d\n", hum());
Now, function hum was declared as returning bool, so how can you get away with printing it as a %d? Don't the extra arguments you pass to printf, and the %-specifiers you use in the format string, have to match exactly?
Yes, they do have to match, but there are three additional factors. First, there is no %-specifier for bool. Second, there's also an additional set of rules that comes into play, because printf is special. Third, since a Boolean value is actually just a number, 0 or 1, we will find that underneath, type bool is actually going to be implemented as an integer type, int or short int or char.
Since printf accepts a variable number of arguments, something called the default argument promotions come into play. These say that every integer type smaller than int is automatically promoted to int, and also (though it doesn't matter here), that type float is promoted to double. So function hum's return value gets promoted from bool to int, and it's perfectly fine to print it with %d.
bool. So please pick the language you want an answer for and do not tag the other one. I assume that you ask about C++ and not C, because the shown code does compile as C++ but not as C. E.g. here tutorialspoint.com/compile_c_online.php and here tutorialspoint.com/compile_cpp_online.phphum2is returning a boolean type here? It's clearly returning anint.