What if the integers are so large that a*b
is larger than the maximum
value that can be stored in a variable of the integer type.
Signed integer overflow is undefined behavior.
Will the compiler notice that the target type can hold larger values
and convert the values to double
first, or will the multiplication
just flow over / wrap around?
Since it's undefined, the compiler is allowed to do anything. That includes doing the computation in double
, ignoring the overflow and returning whatever the underlying hardware returns, formatting your hard drive, making your cat pregnant, or anything in between.
Most compilers would probably ignore it most of the time, and use "overflow is UB" to optimize your code the rest of the time, which then blows up spectacularly. There's a nice example on SO: Why does integer overflow on x86 with GCC cause an infinite loop?