Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ rely on implicit conversion to bool in conditions?

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?

like image 804
moala Avatar asked Aug 25 '09 22:08

moala


People also ask

Does C allow implicit conversion?

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.

What happens in implicit conversion?

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.

What is implicit conversion give an example?

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.

What is implicit conversion in SQL Server?

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.


1 Answers

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.

like image 63
Mark Ransom Avatar answered Sep 18 '22 10:09

Mark Ransom