0

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?

1
  • 2
    Tangent: Prefer static_cast<long long>(i) over a C-style cast. Commented Jun 24, 2021 at 15:55

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.