Why we are using static_cast to NULL

653 views Asked by At

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

There are 2 answers

7
Lightness Races in Orbit On BEST ANSWER

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.

5
Cheers and hth. - Alf On

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.