Context : We have business requirement that a value is reported at 3 or 4 digit string. If the string is 3 digits, it’s value is actually *10.
e.g. 123 represents 1230, where as 4567 represents 4567.
When converting back from a stored integer to the string, the above code is seen as one way to determine this. The question we have is would the optimizer remove this code for x (integer and float). Specifically looking at Java, but the follow on question is how would other languages behave
The obvious other way to do this is use Mod (x%10).
Your question makes a false presumption that
(x/10)*10necessarily equalsx. In general, Java compilers and virtual machines are allowed to optimize anything any way they want to so long as they satisfy the requirements of the Java Language Specification.If
xis afloator adoublethenx == (x/10)*10if there is no floating point rounding error. However, 10 is anintand ifxis anintorlongthen the expression uses Integer division. The Java Language Specification is crystal clear on what the division operator does with respect to integers. Namely it rounds toward zero. So the Java compiler may optimize that expression to something other than a divide followed by a multiply, but whatever the optimizer does, it has to produce the correct result.