Garmaine Staff asked 1 year ago
Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 6 hours ago.

I'm reading A Tour of C++ by Bjarne Stroustrup to brush up on my C++.

In Chapter 1, section 1.8, Stroustrup writes:

The most common case is testing a variable against 0 (or the nullptr). To do that, simply leave out the explicit mention of the condition. For example:

void do_something(vector<int>& v)
{
    if (auto n = v.size()) {
        // ... we get here if n!=0 ...
    }
    // ...
}

In my own code, I always try to be explicit, and to accurately convey my intention. I believe that this is considered a general programming best practice.

I consider writing elaborate expressions that evaluate to logical true or false (rather than to 0 or nullptr) as part of this approach. It can also help to avoid subtle implicit casting bugs. In fact, I would think that modern C++ allowed this kind of implicit conversion only for backward compatibility purposes, and would actually expect it to be discouraged in new code.

At the same time, I believe that in his book, Stroustrup suggests best practices that are generally accepted by the community.

My questions are:

  1. Is this style of implicit conversion really considered a best practice in the C++ development community?
  2. If so, doesn't it contradict other best practices and the general underlying goals of strong typing?