Reputation: 485
I would like to multiple 2 positive signed 32-bit integers i
and j
. The worst case scenario is when i
and j
are both INT_MAX
where their product is within the limit of a 64-bit integer, but when I perform the operation
int i = INT_MAX;
int j = INT_MAX;
long long int res = i * j;
I get garbage due to integer overflow. So I've typically solved that problem by casting i
or j
to a long long int
int i = INT_MAX;
int j = INT_MAX;
long long int res = (long long int)i * j;
Is this the typical workaround for this issue? Are there other ways that may be better?
Upvotes: 0
Views: 796
Reputation: 179819
Your solution is correct, and standard enough that quality compilers will recognize it. Some CPU's have dedicated 32x32->64 multiplication instructions, and you can reasonably expect a compiler to use such an instruction despite the cast.
Upvotes: 3