A random assignment
-
I encountered the following line of (C++) code today, along with a few more like it:
totalcost = rnd((totalcost += cost), 2);
Now, as far as I can see, there's a few things wrong:
- The += is pointless - it should just be a +
- rnd() does not return a random number like in every other program/language I've seen. It rounds the 1st argument to the number of decimal places specified by the 2nd.
- totalcost and cost are double-precision floating point numbers. Ever rounded a floating point number and got the expected result? rnd() actually converts the double to a decimal, rounds it, then converts it back to a double.
-
@mxsscott said:
The += is pointless - it should just be a +
No, it's definitely very pointful. It tries to invoke undefined behaviour but fails because the function call creates a sequence point.
-
Ah indeed. I forgot to mention my quick research into sequence points after thinking undefined thoughts!
-
@Vempele said:
@mxsscott said:The += is pointless - it should just be a +
No, it's definitely very pointful. It tries to invoke undefined behaviour but fails because the function call creates a sequence point.It would suck, though, if rnd() were redefined as a macro...
-
@alegr said:
@Vempele said:
@mxsscott said:The += is pointless - it should just be a +
No, it's definitely very pointful. It tries to invoke undefined behaviour but fails because the function call creates a sequence point.It would suck, though, if rnd() were redefined as a macro...
(Un)fortunately rnd() is defined as a function in a file that gets passed through an Informix ESQL/C precompiler because it calls deccvdbl(), decround() then dectodbl() in the Informix client library. A macro sounds like too easy a way to break the calculation.