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!
Subtle coding error Subtle coding error Reviewed by Sourabh Soni on Saturday, January 30, 2010 Rating: 5

No comments

Author Details

Image Link [https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZYEKEHJPev0oC4dyp_vZFA3Q6PM99sbRGRgel5lr3s9PJPKQORaMDhc5f0wLqZjHSE79OnUom2STt1asn17AKrN2FPD6gH6gjz4sCmL-fCfCp5ksFbAT6sqxx02KLzi2C_Q2kSMTtQhIM/s1600/sourabhdots3.jpg] Author Name [Sourabh Soni] Author Description [Technocrat, Problem Solver, Corporate Entrepreneur, Adventure Enthusiast] Facebook Username [sourabh.soni.587] Twitter Username [sourabhs271] GPlus Username [#] Pinterest Username [#] Instagram Username [#] LinkedIn Username [sonisourabh] Youtube Username [sonisourabh] NatGeo Username [271730]