Subtle coding error
Here is an another case of implementation error that I recently encountered. It took more than 4 days for my fellow developer to locate the bug and it was a real nightmare for him. Look at following piece of C++ code:
x = 1.0 / val * val;
where, x and val are variables of double data-type.
Obliviously, this code is not incorrect! As the operator '*' and '/' has same precedence and are executed in left-to-right order, it mean variable 'x' will always get 1.0 value assigned.
The intended and correct code is:
x = 1.0 / (val * val);
Happy and safe coding!
x = 1.0 / val * val;
where, x and val are variables of double data-type.
Obliviously, this code is not incorrect! As the operator '*' and '/' has same precedence and are executed in left-to-right order, it mean variable 'x' will always get 1.0 value assigned.
The intended and correct code is:
x = 1.0 / (val * val);
Happy and safe coding!
Subtle coding error
Reviewed by Sourabh Soni
on
Saturday, January 30, 2010
Rating:
No comments