Question

I've found that this boilerplate code appeared frequently in my program:

if (ptr) {
  ptr->method();
}

and I've replaced it with a single-liner (like I saw people do it in Java):

ptr && (ptr->method(), true);

Is this a good practice from the standpoint of generated machine code or am I introducing additional constants into my binary? What possible issues might this "port" from Java cause in my program?

Was it helpful?

Solution

From the standpoint of generating machine code, this is completely irrelevant. If one of these two forms is better and a compiler's optimiser is not capable of converting one to the other, it's not worth the name "optimiser," period.

This leaves just the question of which is more readable. The first one is immediately obvious. The second one will easily take a human more than a minute to parse. Not good.

Also note that the second case might introduce unwanted results in the presence of operator overloading. If operator , is overloaded for the type which method() returns, it will get called in the 2nd case, not in the first. If operator && is overloaded for the type of ptr, the 2nd case will simply fail since overloaded && is not lazily evaluated. However, both of these operators are among those whose overloading is strongly discouraged.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top