Next Previous Contents

13. When using the ?: operator, cast values that are not ints

The result type of the ?: operator is a long, if one of the second or third operands is a long. If the second operand has been evaluated and it was of type int, and the compiler detects that the third operand is a long, it has to add an additional int -> long conversion for the second operand. However, since the code for the second operand has already been emitted, this gives much worse code.

Look at this:

        long f (long a)
        {
            return (a != 0)? 1 : a;
        }

When the compiler sees the literal "1", it does not know, that the result type of the ?: operator is a long, so it will emit code to load a integer constant 1. After parsing "a", which is a long, a int -> long conversion has to be applied to the second operand. This creates one additional jump, and an additional code for the conversion.

A better way would have been to write:

        long f (long a)
        {
            return (a != 0)? 1L : a;
        }

By forcing the literal "1" to be of type long, the correct code is created in the first place, and no additional conversion code is needed.


Next Previous Contents