Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to #define NULL nullptr?

I have seen below macro in many topmost header files:

#define NULL 0  // C++03 

In all over the code, NULL and 0 are used interchangeably. If I change it to.

#define NULL nullptr  // C++11 

Will it cause any bad side effect ? I can think of the only (good) side effect as following usage will become ill-formed;

int i = NULL; 
like image 841
iammilind Avatar asked Jan 25 '12 13:01

iammilind


People also ask

Is it safe to fly now?

If you've had all recommended COVID-19 vaccine doses, including boosters, you're less likely to become seriously ill or spread COVID-19 . You can then travel more safely within the U.S. and internationally. But international travel can still increase your risk of getting new COVID-19 variants.

Is it safe to fly in the rain?

Rain is not actually dangerous to aircraft, and you can often fly through rain with no issues at all. The main problem is that heavy rain often leads to poor visibility. Again, whether or not you can fly in heavy rain depends on your qualifications and what sort of instrumentation your aircraft has.


2 Answers

I have seen below macro in topmost header file:

You shouldn't have seen that, the standard library defines it in <cstddef> (and <stddef.h>). And, IIRC, according to the standard, redefining names defined by standard header files results in undefined behaviour. So from a purely standardese viewpoint, you shouldn't do that.


I've seen people do the following, for whatever reason their broken mind thought of:

struct X{   virtual void f() = NULL; } 

(As in [incorrectly]: "set the virtual table pointer to NULL")

This is only valid if NULL is defined as 0, because = 0 is the valid token for pure-virtual functions (§9.2 [class.mem]).

That said, if NULL was correctly used as a null pointer constant, then nothing should break.

However, beware that, even if seemingly used correctly, this will change:

void f(int){} void f(char*){}  f(0); // calls f(int) f(nullptr); // calls f(char*) 

However, if that was ever the case, it was almost certainly broken anyways.

like image 84
Xeo Avatar answered Sep 20 '22 17:09

Xeo


Far better is to search and replace NULL with nullptr throughout the code.

It may be syntactically safe, but where would you put the #define? It creates code organisation problems.

like image 33
spraff Avatar answered Sep 18 '22 17:09

spraff