jason
jason

Reputation: 474

Why the numeric promotion of integer and double operands not happen?

In my recent work, I met a question, which is about the numeric promotion of some operands. The following is the demo code:

int num1 = 9999999;
int num2 = 65536;
double result = num1*num2*1.0;

In my opinion, I thought both of num1 and num2 will be automatically promotion to double and then calculate the result as one of the operands is a double, while the result shocked me. I got a negative number. And then I look into the JLS, it also says it should do the numeric promotion, see below:

"If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.

If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).

Otherwise, the operation is carried out using 32-bit floating-point arithmetic, and the result of the numerical operator is a value of type float. (If the other operand is not a float, it is first widened to type float by numeric promotion.)"

And if I change the result to 1.0*num1*num2, it will give me the right answer. Could anybody tell me what the hell is this.

Upvotes: 1

Views: 345

Answers (2)

User27854
User27854

Reputation: 884

This has to do with operator precedence,

In your case what is happening is num1 and num2 are integers and they are calculated first and their result is also an integer, since the result is out of range its getting wrapped around thus you are getting the result in negative, the next step is multiplication with 1.0. Here as you expect the result is promoted to double. But now we are aware that its too late.

You can try any of these

result=num1*1.0*num2;
result=1.0*num2*num1;
result=1.0*num1*num2;

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500495

No, the result of num1 * num2 is promoted to double. Your statement is equivalent to:

double result = (num1 * num2) * 1.0;

So with promotion, that would be:

int firstMultiplication = num1 * num2;
double promoted = firstMultiplication;
double result = promoted * 1.0;

Basically, this is just a matter of operator precedence. Numeric promotion happens to operands - not every expression which was involved in evaluating that operand to start with.

Upvotes: 7

Related Questions