zeke
zeke

Reputation: 195

Why does implicit type conversion results incorrectly in this code?

#include <iostream>

int main()
{
    int number=65536;
    long long temp=number*number;
    std::cout << temp << std::endl;
    return 0;
}

Square of 65536 is obviously out of int's range. Now, if I had declared temp as an int, I would understand why this fails. But even though it's long long , the output is always 0. I believe this is somewhat related to implicit type conversion but I can't understand why the result is 0.

Is this because c++ simply doesn't allow converting int to long? If so, then why does this work with smaller numbers?

Upvotes: 3

Views: 135

Answers (3)

Lundin
Lundin

Reputation: 213513

The type used for an operation depends on the operands used by that operation.

In the operation number*number, both operands are int. They are not small integer types and they are both of the same type, so there will be no implicit promotion. The multiplication will get carried out on type int and the result will be of type int.

That you happen to assign the result to a long afterwards doesn't affect the calculation at all.

The solution is to cast one or both operands to a type large enough to hold the result of the calculation.

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234655

(Note that the range of an int can be as small as -32767 to +32767.)

number * number is evaluated in int arithmetic since both arguments are of type int. The behaviour of your program is undefined due to your int overflowing.

The fact that you want to assign the result to a long long is not relevant.

One solution would be to write 1LL * number * number to force promotion of the arguments to long long types.

Upvotes: 10

Some programmer dude
Some programmer dude

Reputation: 409166

The compiler treats the multiplication as a multiplication between two int variables. It is the result of that multiplication that is converted to a long long for the initialization of the temp variable.

At least one of the operands of the multiplication needs to be a long long for overflow to not happen.

Upvotes: 2

Related Questions