Initialise in condition, not assign

I’ve read a lot of code polluted with assignments in condition:

T* p;
if (ptr = source())
{
    ...
}
else
{
    ...
}/

Presumably, it is preferred of someone who is really after shortcuts in code. If you must cut short, reconsider it and at least write this:

if (T* p = source())

It is a perfect shortcut through several features at once: initialisation, condition and scope encapsulation. The scope of p is narrowed to the if-else condition only:

if (T* ptr = source())
{
    ...
}
else
{
    ...
}/

And, it feels and works like using statement in C#. Perhaps that will convince C/C++ legacy crowd ;-)

Thanks to Jonathan Wakely from ACCU for inspiring discussion(s).

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>