Sunday, October 24, 2021

[SOLVED] What are the int64_t range limits on x86?

Issue

Testing some integer multiplications on x86.

int32_t a = 2097152;
int64_t b = a * a;

Why does the above b evaluate to zero?


Solution

What are the int64_t range limits on x86?

C11 standard 7.20.2.1 says [-2^64; 2^64-1] which is equivalent to [-9223372036854775808;9223372036854775807] You can get it by printing INT64_MAX and INT64_MIN.

Why does the above b evaluate to zero?

Because the promotion does not take place until the multiplication has been evaluated. The result of a*a is of type int32_t and when you overflow a signed integer you invoke undefined behavior. What you're doing is essentially this:

int32_t a = 2097152;
int32_t tmp = a * a;
int64_t b = tmp;

You can get the desired result with:

int32_t a = 2097152;
int64_t b = (int64_t) a * a;


Answered By - klutt