Khushi Mittal
Khushi Mittal

Reputation: 33

Why is a Static Cast necessary to avoid overflowing int in a mathematical operation when the result will be stored in a variable large enough?

I have two integers, m and k. The product of m and k might overflow an int datatype, so I used long long int data type but I was still getting runtime error:

signed integer overflow: 89945 * 32127 cannot be represented in type 'int' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:14:28.

However when I used,

long long int b = static_cast<long long>(m) * static_cast<long long>(k);

it worked! So my doubt is why is casting m and k into long long int mandatory here?

Upvotes: 0

Views: 80

Answers (0)

Related Questions