1

I have an int64_t variable. When I add another int64_t variable

and convert it to a double to print it on the serial monitor, it acts as if it was a int32_t variable. This is the program:

int64_t a = 1 << 31;
double b = static_cast<double>(a);
Serial.println(b);

The output on the serial monitor is -2147483648.00.

What is going on?

LukasFun
  • 295
  • 1
  • 4
  • 17

1 Answers1

3

1 << 31 is interpreted by the compiler as (int)1 << (int)32. See the implicit types of integer literals. The rules of usual arithmetic conversions state that no implicit conversion is performed in this case. The result is then computed as an int, and it overflows. Note that this is undefined behavior. The assignment int64_t a = ... converts the (already overflowed) result to the wider type, without changing its value.

You probably want to write something like:

int64_t a = 1LL << 31;
Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81