#Need help distinguishing between NULL, nullptr and 0

26 messages · Page 1 of 1 (latest)

lapis stirrup
#

Hello guys, C++ is my first programming language I chose to delve into and have just scratched the basics. One thing I recently am confused about is these keywords I mentioned in the title. It would be quite helpful if someone can brief me about them as these terms are used many places and I don't know if they are replacebly same or different.
One time I saw 0 and NULL in srand(time()) and other time I saw a pointer being initialized to nullptr and NULL so I am quite confused as a beginner

rose crystal
#

NULL is a remnant from C and should not be used in C++

lapis stirrup
#

Oh

#

I see

rose crystal
#

it's basically just a

#define NULL 0
#

and exists solely for backwards compatibility with C

forest kiln
#

i know NULL is basically 0 on every compiler but iirc it's is implementation defined?

lapis stirrup
#

I saw it being used to initialize a pointer for dynamic allocation of memory

rose crystal
#

in C, it used to serve the purpose of a null pointer constant

#

but at have nullptr for that

lapis stirrup
#

I see

#

I can use nullptr then

rose crystal
#

yes

#

never use NULL in C++. ever.

lapis stirrup
#

but I heard that we should not dereference a nullptr, is that true?

rose crystal
#

well, what would be the meaning of doing that?

forest kiln
#

(yes dereferencing a nullptr is undefined behaviour)

lapis stirrup
#

I see

hazy trail
#

(random remark that C23 has/will have nullptr so arguably you should stop using NULL in C as well unless you're writing C code that has to be compatible with old C standards, which I guess is fairly common)

forest kiln
#

keep in mind that you use nullptr's when working with pointers, and when it is not pointing to something, people coming from other languages might believe that NULL/nullptr is the equivalent of null in like js or C#

lapis stirrup
hazy trail
rose crystal
lapis stirrup
lapis stirrup
#

Thank you guys I think I will close it, its still advanced for me ig