For example, when I'm dividing two ints and want a float returned, I superstitiously write something like this:
int a = 2, b = 3;
float c = (float)a / (float)b;
If I do not cast a
and b
to floats, it'll do integer division and return an int.
Similarly, if I want to multiply a signed 8-bit number with an unsigned 8-bit number, I will cast them to signed 16-bit numbers before multiplying for fear of overflow:
u8 a = 255;
s8 b = -127;
s16 = (s16)a * (s16)b;
How exactly does the compiler behave in these situations when not casting at all or when only casting one of the variables? Do I really need to explicitly cast all of the variables, or just the one on the left, or the one on the right?
int a = 2, b = 3;
float c = static_cast<float>(a) / b; // need to convert 1 operand to a float
Five rules of thumb to remember:
The ANSI C rules are as follows:
Most of these rules also apply to C++ though not all types are officially supported (yet).
Overflow is always a problem. Note. The type of the result is the same as the input operands so all the operations can overflow, so yes you do need to worry about it (though the language does not provide any explicit way to catch this happening.
As a side note:
Unsigned division can not overflow but signed division can.
std::numeric_limits<int>::max() / -1 // No Overflow
std::numeric_limits<int>::min() / -1 // Will Overflow
In general, if operands are of different types, the compiler will promote all to the largest or most precise type:
If one number is... And the other is... The compiler will promote to... ------------------- ------------------- ------------------------------- char int int signed unsigned unsigned char or int float float float double double
Examples:
char + int ==> int signed int + unsigned char ==> unsigned int float + int ==> float
Beware, though, that promotion occurs only as required for each intermediate calculation, so:
4.0 + 5/3 = 4.0 + 1 = 5.0
This is because the integer division is performed first, then the result is promoted to float for the addition.
You can just cast one of them. It doesn't matter which one though.
Whenever the types don't match, the "smaller" type is automatically promoted to the "larger" type, with floating point being "larger" than integer types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With