vicentazo
vicentazo

Reputation: 1799

Type casting when exceeding the limit

I want to multiply two int numbers and, in order to prevent exceeding the int limit (2147483647), the result is saved in a long long variable. So, I try this piece of code:

int a, b;
long long result = a * b;

and it doesn't work! If a=50000 and b=50000 then result=-1794967296.

Therefore, I have to apply a type casting to a and b:

int a, b;
long long result = (long long)a * (long long)b;

Why is it necessary to apply a type casting in this case?

Note: I don't want to change the data type of a and b, I need to keep them as int.

Upvotes: 2

Views: 848

Answers (4)

abo-abo
abo-abo

Reputation: 20342

You don't need to cast both a and b. Just a is enough.

Just think that you're the compiler and you're asked: take two things, combine them and place them over there.

That's two instructions: combine and place. And the second one should not care about the first one if you're using a speedy language like C.

What does help you is that combine cares about what it combines. Now you just need to state it clearly and cast one of the operands to long long.

You might think that place could be smarter, and it actually should be smarter, but there also should be a clearly defined limit to how smart it should be, otherwise we get that story from Space Odyssey 2001 :).

Upvotes: 2

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

Since a and b are int, their product a*b is int also. But the product is so big that it overflows and you get an incorrect value.The cast is needed so that the product is also long long.

By the way, you don't need to cast both operands. Just one is enough:

long long result = a * (long long)b;

The other one is promoted to long long also. See this online demo.

By the way, prefer C++-style cast over C-style cast:

long long result = a * static_cast<long long>(b);

Hope that helps.

Upvotes: 7

denidare
denidare

Reputation: 474

Because the result of a int * int multiplication is an int itself, so the result is an int that is then converted to a long long but overflow has already occurred.

But if you cast the a and b variables to a long long before the multiplication (or just one of them), the result is a long long. Remember:

int * int --> int 
long long * long long --> long long
long long * int --> long long

Upvotes: 2

Pete Becker
Pete Becker

Reputation: 76315

In an arithmetic expression like a * b the compiler looks at the types of the arguments and does the corresponding operation. In this case, both a and b have type int, so the compiler multiples the two int values, producing a result of type int.

To do the calculation at higher precision, one or both of the arguments must have that precision. So you need to change either a or b (or both) to long long in order to get the compiler to generate code that multiplies two long long values.

Upvotes: 3

Related Questions