I found the following rule in a coding standards sheet :
Do not rely on implicit conversion to bool in conditions.
if (ptr) // wrong
if (ptr != NULL) // ok
How reasonable/usefull is this rule?
How much overload on the compiled code?
Implicit Type Conversion is also known as 'automatic type conversion'. It is done by the compiler on its own, without any external trigger from the user. It generally takes place when in an expression more than one data type is present.
An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.
Implicit conversions: No special syntax is required because the conversion always succeeds and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
Implicit conversions are not visible to the user. SQL Server automatically converts the data from one data type to another. For example, when a smallint is compared to an int, the smallint is implicitly converted to int before the comparison proceeds.
In the strictest sense, you can rely on implicit conversions to bool. Backwards compatibility with C demands it.
Thus it becomes a question of code readability. Often the purpose of code standards is to enforce a sameness to the code style, whether you agree with the style or not. If you're looking at someone else's standard and wondering if you should incorporate it into your own, go ahead and debate it - but if it's your company's long-standing rule, learn to live with it.
P.S. I just joined an organization that has the same rule. I'm actually fine with it because I've always believed that explicit is better than implicit. The one thing I can't abide though is bool condition; ... if (condition == true)
, which so redundant that it grates on my eyes.
Any decent compiler should generate the same code whether the check is implicit or explicit, so that shouldn't be a consideration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With