The right way to do it is straight-forward:
int hours = /*some_number*/;
int wage = 100*hours;
if (hours > 40) wage += 50 * (hours-40);
To squeeze it to a single expression, the example takes advantage of the fact that a boolean is either 1 or 0. So x*some_bool
evaluates to either x
or 0
.
In your case, if (hours > 40)
then
(50*(hours-40))*(hours>40) == (50*(hours-40)) * 1 == 50*(hours-40)
otherwise it is 0
.
(50*(hours-40))*(hours>40) == (50*(hours-40)) * 0 == 0
In general it is less readable to write code this way. The only valid uses IMO are in advanced algebraic transformations used in cryptography or complexity theory.
solved What is this boolean operation? `expression * boolean` [closed]