8

When I try to study QP/CPP code I came across below line.

QTimeEvt *t; // ... if (t == static_cast<QTimeEvt *>(0)) { 

Why they are doing static_cast of 0? If they want to check NULL we can do that directly right?

This source code you can find out in

http://www.state-machine.com/qpcpp/qf__time_8cpp_source.html

2 Answers 2

11

Yeah, that's unnecessary, though it may be mandated by some style guide for "clarity", or it may be there to silence an overzealous static analysis tool.

Of course, nowadays, we'd just write nullptr and leave it at that.

Sign up to request clarification or add additional context in comments.

7 Comments

@M.M: Somewhat less preferable.
@LightnessRacesinOrbit whats the problem with !t ?
@GilsonPJ: Not self-documenting, doesn't hard-error when you change what t is (accidentally or otherwise) etc etc. (I'm being a bit picky. I like to use the type system, though. Its job is to aid in ensuring program correctness, and writing out == nullptr is hardly expensive.)
@GilsonPJ: It doesn't; I didn't say it does.
@GilsonPJ :i don't like (!t). The reason being is the expression (t) is not boolean, it is pointer. I prefer only applying !, && & || only to boolean expressions (and that means if they are not boolean expressions, they are rewritten so they are).
|
4

The idiomatic way to write

QTimeEvt *t; // ... if (t == static_cast<QTimeEvt *>(0)) { 

… is

QTimeEvt* t; // ... if( !t ) { 

Or you can write it as

if( not t ) { 

… although you can also write

if( t == nullptr ) { 

… or, ¹C++03-style,

if( t == 0 ) { 

There's no need for the cast.

It's just verbiage consuming the reader's time.

Notes:
¹ If the <stddefs.h> header is included one can write NULL instead of 0 where a nullpointer is required. With a modern implementation NULL might even be defined as nullptr.

5 Comments

if( not t ) Is this commonplace?
Didn't know NULL can be nullptr since C++11 — good to find out!
@LightnessRacesinOrbit: I don't know about how common it is. As far as I know there is no global code inspection service, as Google Code View once provided. I do know that with Visual C++ you have to include the C header <iso646.h> to use not, that is, MSVC is not standard-conforming here. I use a forced include to make it more conformant.
That's pretty grim.
Yep. But then, by default MSVC doesn't even support standard main for its most common use… Heh. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.