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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It looks like you are using a platform where
intandlonghave the same size. (I’ve inferred this by the fact that iflongwas able to hold all the valid values ofunsigned intyou would not see the behaviour that you are seeing.)This means that in the expression
a*z, bothaandzare converted tounsigned longand the result has typeunsigned 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.”)cis the result of converting this expression fromunsigned longtolongand in your case this results in an implementation defined result (that happens to be negative) as the positive value ofa*zis not representable in a signedlong. Inc/1000,1000is converted tolongandlongdivision is performed (no pun intended) resulting in along(which happens to be negative) and is stored tod.In the expressions
a*z/1000,1000(an expression of typeint) is converted tounsigned longand the division is performed between twounsigned longresulting in a positive result. This result is representable as alongand the value is unchanged on converting tolongand storing tob.