Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weird calculation result

Tags:

c++

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.

like image 894
crushanator Avatar asked Apr 01 '12 13:04

crushanator


Video Answer


1 Answers

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.

like image 133
CB Bailey Avatar answered Sep 20 '22 01:09

CB Bailey