why d
is not equal b
in this example?
unsigned int z = 176400;
long a = -4;
long b = a*z/1000; //b=4294261
long c = a*z; // c=-705600
long d = c/1000; // d =-705
I use Visual Studio 2008, windows XP, core2duo. Thanks.
It looks like you are using a platform where int
and long
have the same size. (I've inferred this by the fact that if long
was able to hold all the valid values of unsigned int
you would not see the behaviour that you are seeing.)
This means that in the expression a*z
, both a
and z
are converted to unsigned long
and the result has type unsigned long
. (ISO/IEC 14882:2011, 5 [expr] / 9 ... "Otherwise, both operands shall be converted to the unsigned integer type corresponding to the type of the operand with signed integer type.")
c
is the result of converting this expression from unsigned long
to long
and in your case this results in an implementation defined result (that happens to be negative) as the positive value of a*z
is not representable in a signed long
. In c/1000
, 1000
is converted to long
and long
division is performed (no pun intended) resulting in a long
(which happens to be negative) and is stored to d
.
In the expressions a*z/1000
, 1000
(an expression of type int
) is converted to unsigned long
and the division is performed between two unsigned long
resulting in a positive result. This result is representable as a long
and the value is unchanged on converting to long
and storing to b
.
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