C++ :: Casting A Logical Boolean As Int?
Jun 8, 2013Let's say I have a product that needs service after 500 hours at 100 RPM. I can dsiplay the remaining hours only as an integer and we only have integer math. Management wants it to display 500 for the first hour, not 499 after the first minute is ticked off. But after a few minutes fullHours will be 499 and partialHours will have some value. I have 3 ways to determine displayHours to suit management and I want to know if the first is ligit.
short fullHours = 500;
short partialHours = 0;
short displayedHours = 0;
// Method 1 - Is is Kosher to cast a boolean as an int? Is TRUE always a 1 or is that a bad assumption?
displayedHours = fullHours + (short) (partialHours != 0);
//Method 2 - Works but some have disdain for the ternary conditional
displayHours = fullHours + (partialHours ? 1 : 0);
//Method 3 - seems a bit pedantic
displayHours = fullHours;
if (partialHours != 0) {
displayHours++;
}