3

I'm studying the only instance now(in c++), and I tried the following code in my .cpp file.

#include "OnlyInstance.h"

OnlyInstance* OnlyInstance::instance = NULL;
..........

but the compiler told me "error C2065: 'NULL' : undeclared identifier". So is that means, I should

#include <stdio.h> 

in front of it? But I also included stdio.h in the main file. So stdio.h will be included many times when compiling, right? How can I use NULL correctly?

Another question is that, I know I can use 0 instead of NULL, but which way is more recommended in c++?

1
  • 1
    As an aside, as you are initializing a static pointer with NULL, you could also simply omit the initializer. Commented Feb 10, 2015 at 21:45

2 Answers 2

11

NULL is defined in various headers, for example in <cstddef>.

You should however prefer nullptr over NULL if your compiler supports this.

Including a header multiple times is no problem (if the header is not horribly broken, which the standard headers are not).

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

2 Comments

which it should for C++11 and later.
But if I do #include <stdio.h> in OnlyInstance.cpp and main.cpp at the same time, then #include 'OnlyInstance.h' in main.cpp. What will the compiler do? stdio.h will be included twice? Thank you!
5

NULL is only a define with a value of 0. It is exactly the same.

But if you have access to C++11, I would recommend using nullptr.

4 Comments

Actually, it can be something else. Which is one of the reasons to prefer nullptr.
Technically, it is a 0 of the same size as a pointer, so it may be 0 or 0L or 0LL depending on what integer type matches a pointer. Otherwise, things like printf("%p", NULL); will go wrong.
@MatsPetersson: That would be nice, sometimes, for hiding errors. It isn't guaranteed though.
Ok, it may not apply to ALL compilers, but it certainly worked better in my experience than the printf("%p", 0); that some test-code I had to deal with when I implemented printf - it took a while to identify the problem, as it was hidden a little better than the code in this comment...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.