Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we are using static_cast to NULL

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

like image 979
Gilson PJ Avatar asked Dec 23 '16 00:12

Gilson PJ


People also ask

What is the purpose of static_cast?

The static_cast operator can be used for operations such as converting a pointer to a base class to a pointer to a derived class. Such conversions are not always safe.

Will static_cast return null?

No. If the pointer refers to a valid object, and the conversion is valid, then the result will also refer to a valid object, so it won't be null.

What static_cast is actually doing?

static_cast can be used to convert between pointers to related classes (up or down the inheritance hierarchy). It can also perform implicit conversions.

Should I use static_cast?

You shouldn't use static_cast for casting down an inheritance hierarchy, but rather dynamic_cast . That will return either the null pointer or a valid pointer.


1 Answers

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.

like image 189
Lightness Races in Orbit Avatar answered Sep 30 '22 00:09

Lightness Races in Orbit