Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
question from:https://stackoverflow.com/questions/9003425/is-it-safe-to-define-null-nullptr

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
391 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...