6.7a — Null pointers

Null values and null pointers

Just like normal variables, pointers are not initialized when they are instantiated. Unless a value is assigned, a pointer will point to some garbage address by default.

Besides memory addresses, there is one additional value that a pointer can hold: a null value. A null value is a special value that means the pointer is not pointing at anything. A pointer holding a null value is called a null pointer.

In C++, we can assign a pointer a null value by initializing or assigning it the literal 0:

Pointers convert to boolean false if they are null, and boolean true if they are non-null. Therefore, we can use a conditional to test whether a pointer is null or not:

Best practice

Initialize your pointers to a null value if you’re not giving them another value.

Dereferencing null pointers

In the previous lesson, we noted that dereferencing a garbage pointer would lead to undefined results. Dereferencing a null pointer also results in undefined behavior. In most cases, it will crash your application.

Conceptually, this makes sense. Dereferencing a pointer means “go to the address the pointer is pointing at and access the value there”. A null pointer doesn’t have an address. So when you try to access the value at that address, what should it do?

The NULL macro

In C++, there is a special preprocessor macro called NULL (defined in the <cstddef> header). This macro was inherited from C, where it is commonly used to indicate a null pointer.

The value of NULL is implementation defined, but is usually defined as the integer constant 0. Note: as of C++11, NULL can be defined as nullptr instead (which we’ll discuss in a bit).


Because NULL is a preprocessor macro with an implementation defined value, avoid using NULL.

The perils of using 0 (or NULL) for null pointers

Note that the value of 0 isn’t a pointer type, so assigning 0 (or NULL, pre-C++11) to a pointer to denote that the pointer is a null pointer is a little inconsistent. In rare cases, when used as a literal argument, it can even cause problems because the compiler can’t tell whether we mean a null pointer or the integer 0:

In the likely case where NULL is defined as value 0, print(NULL) will call print(int), not print(int*) like you might expect for a null pointer literal.

nullptr in C++11

To address the above issues, C++11 introduces a new keyword called nullptr. nullptr is a keyword, much like the boolean keywords true and false are.

Starting with C++11, this should be favored instead of 0 when we want a null pointer:

C++ will implicitly convert nullptr to any pointer type. So in the above example, nullptr is implicitly converted to an integer pointer, and then the value of nullptr assigned to ptr. This has the effect of making integer pointer ptr a null pointer.

We can also call a function with a nullptr literal, which will match to any parameter that takes a pointer value:

For advanced readers

A function with a different parameter list is a new function, even if a function with the same name exists. We cover this later (Function overloading).

Best practice

Use nullptr to initialize your pointers to a null value.


C++11 also introduces a new type called std::nullptr_t (in header <cstddef>). std::nullptr_t can only hold one value: nullptr! While this may seem kind of silly, it’s useful in one situation. If we want to write a function that accepts only a nullptr argument, what type do we make the parameter? The answer is std::nullptr_t.

You probably won’t ever need to use this, but it’s good to know, just in case.

6.8 -- Pointers and arrays
6.7 -- Introduction to pointers

91 comments to 6.7a — Null pointers

  • Facundo Flores

    Not very problematic, but doSomething() parameter ptr is never used, gives compiler error:

  • Yashas bharadwaj

    Sir during explanation of nullptr a code was written, wherein nullptr was passed as a argument and it called void print(int *x)what if there where func like void print(float *x)to which nullptr as a argument would have been passed

    • nascardriver

      `nullptr` works for any kind of pointer, it doesn't matter what type the pointer points to. If there are 2 `print` functions and one takes an `int*` and the other a `float*`, the call `print(nullptr)` is ambiguous and you'll get an error.

  • Max

    Something wrong with parser on this page - there are visible "code" tags in square brackets, code and also no bottom menu with links to previous/next page.
    Also - in code blocks #include lines are blank, with no reference to included file.

  • Somto

    For the code under the heading "The perils of using 0 (or NULL) for null pointers", is there a reason why "print(5);" (or any non-zero integer also works), given that 5 is not a memory address that can be passed as an argument to the expected pointer parameter?

  • Robbas

    Hi Alex and Nascar. Since I encountered some difficulties in understanding some concepts. I was wondering if you could please add some notes just to warn people like me that are following the order of your guide, that the following topics will be explained in the next lessons.

    1) "nullptr is both a keyword and an rvalue constant, much like the boolean keywords true and false are."

    What's rvalue constant?

    I searched the site index and saw that it is explained later.


    I'd add your answer that is perfect as a note on why the ODR is not violated in this case.

    "A function with a different parameter list is a new function, even if a function with the same name exists. It's covered later (Function overloading)."

    Thank you again for your work.

  • Kwonk

    I have quite a challenging problem: I was writing some simple code and after hours of debugging and trying to find out where the problem is, I managed to boil the problem down to this. I hope you can help!

    This causes an error: "read access violation. _Pnext was 0xDDDDDDE1."
    But as soon as I change


    , everything works fine.
    One more thing to note: if I delete this piece of code:

    , the code works fine too.

    So the problem must have something to do with pointers and duplicated instances and the use of nullptr. But what?

    I would greatly appreciate it if you could help!

    • nascardriver

      is the opposite of

      Pointers are `true` if they are non-zero, so these are the same

      By checking for `!m_text`, you're only calling `delete` if `m_text` is a `nullptr`. Deleting a `nullptr` has no effect, so you don't get an error, but a memory leak.

      Your problem is any copy of an `A`. When you copy an `A`, the pointer member variables are copied, so `instanceOf_A` and the temporary `ContainerOf_A.m_A` both point to the same memory. The temporary dies first and deletes the string. Then `instanceOf_A` dies and tries to delete the string again. This causes undefined behavior.

      The solution is a copy constructor that creates a deep copy of the string. We talk about this in chapter 9.

      Now, instead of copying the pointer, we allocate a new string and copy the other string into it. That way, each copy of `A` gets its own string.

      As an aside, your compiler is misconfigured. The trailing semicolon after `main` should have caused a compile-time error. Make sure you set up your project according to lesson 0.10.

      • Kwonk

        Ahh. What a dumb mistake... Thanks.

        Alright. I will wait to do this kind of stuff until I've read chapter 9.

        Yeah, I reinstalled all the C++ stuff in Visual Studio Installer the other day so that's why everything isn't configured properly yet.

        Anyway. Thanks again, Nascardriver.

  • chai

    Would love to see an example of a function take a nullptr_t and doing something useful. I don't see the point right now. Thanks.

  • Gacrux

    I may have missed or forgot something along the way, in the second last code, why


    in the same code won't fail to compile due to the one definition rule?

    • nascardriver

      A function with a different parameter list is a new function, even if a function with the same name exists. It's covered later (Function overloading).

  • Dear Teacher,
    Please let me point out that you use to put std:: before cout but in second snippet you do not do that. Regards.

  • Helliarc

    I'm curious, instead of using Boolean checking for null pointer contents, why not declare your own null pointer global variable to point to, that has some sort of special value depending on the pointer type, that can be checked against so that your pointers never contain null, but contain a known value that you can check against? Does that work but just add unnecessary complexity? I feel like accidently calling garbage or false from a pointer that hasn't been instantiated is more messy than getting an expected return if you call a null pointer that you've assigned to a glaring value. Do you want to null crash during error checking, instead of review logs and search for error results? I'm also still trying to wrap my head around the usefulness of null pointers, so my question could be way out of bounds...

    • Comparing is slow and you need to implement a comparison operator for all types. You can't do this for existing types.
      You're wasting memory because you need to store your special types.
      Not all types can be special. How'd you define a special `int` for example? All values are valid.

      • Helliarc

        I'd imagine using an integer value outside of the acceptable or expected range of valid values. For error checking purposes (debugging), I'd assume the expense of comparators a reasonable expense, one that can easily be changed to real null pointers in the end to drastically optimize the final product. (I read a similar story, where a developer hid a large array until they came up to the end and we're just barely over budget, and the developer said "ah ha!" And removed his buffer array to make the project under budget. That's not exactly how the story goes, I don't do it justice, but I can find the source of you aren't familiar with it.) One argument I can tell myself is that it's not very reader friendly... So anyone else using my code would go straight to null pointers and have no awareness of my "special" pointers... Good talk!

        • Helliarc

          And now that I think about it... That's a lot of memory for all those special types... Toooo much memory! Thanks!

        • > using an integer value outside of the acceptable or expected range of valid values
          So you want to add a special invalid integer for every place you use an integer pointer at? That's a lot of time you could be spending doing something else. There are still scenarios in which there is not unacceptable range, so you can't use a special int.

          > I read a similar story
          I read a similar story :)

          Finding a `nullptr` is also faster than your idea. If you see a pointer and it points somewhere, how do you know it's your special value? You'd have to look it up.
          If your program doesn't do what you want it to do, you have to see if there's a special pointer somewhere.
          If you see a `nullptr`, you know that it's special. If you accidentally have a `nullptr`, you'll notice it, because your program most likely crashes. If you're accessing an invalid pointer, you'll get undefined behavior, with and without nullptr or special pointers. There aren't terribly many reasons to use regular pointers. You'll learn about smart pointers later, but you can do that now too. They handle all the deallocations for you.

          • Helliarc

            Great info. I'm focusing on pointers right now, one of your comments alarm me, though:

            >"There aren't terribly many reasons to use regular pointers"

            Is this just "relatively speaking"?  Or do you mean null pointers? The more I read about pointers, the more simple they seem, I keep getting hung up on when to pass by reference, when to pass a pointer, when to dereference to change the argument... Once I can 'whoosh' through the thought process of pointers I can see them becoming trivial, but I still see them everywhere in code (especially the STL, which I've yet to start swimming through). One thing I can't wait to solve is the arguments in main that most open source code has, there's just so much flipping stuff to learn! I'm trying to stay away from developing my own projects for now, and refraining from googling every problem I run into, I felt like it was giving me bad habits (using namespace std;). I'm having a blast, though... Just finished a hefty tutorial on Boolean algebra last week. Thanks again for your time and persistence with keeping this resource current, I'll be a software developer!

            • "Pointers" was a poor choice on my side. What I meant is "manual dynamic allocations", which hasn't been covered yet, so it's not really relevant to your idea.

              > One thing I can't wait to solve is the arguments in main that most open source code
              It's at the end of chapter 7.

  • Fernando Rosendo

    What if we zero initialize a pointer?

    Is that equivalent to:

    Or equivalent to:

    Or neither?

  • zohreh

    void* p = nullptr;

    is it right?

  • Eat my eggplant

    Hey Alex, In 2ND example at (nullptr in C++11) Is it necessary
    to include<cstddef> to use nullptr?
    Or is it from the core language?
    If it was necessary then replace the comment //for NULL. With //for nullptr
    If not then delete the include.
    Thanks for this tutorial it's awesome <3

  • Alireza

    Hi there,
    I can access NULL without including <cstddef> !

    • You included some header that includes some header that defines NULL.
      If you want to use NULL, include a header that defines it to make sure you code works with all compilers.
      Don't use NULL, use nullptr.

      • Alireza

        Thanks for replaying,
        And how can I know what headers included in <iostream> or some other ?

        • You can look it up in the standard or documentations, eg.

          It's better not to rely on any transitive includes. That way, removing includes won't cause errors in seemingly unrelated code.

  • Dimitri

    Hi nascardriver and Alex!

    !true == false ,its simple

    but what does !x mean? x vice versa?!

    I have a problem with understanding this

  • Ah, the introduction to the programming phenomenon its own inventor called "The Billion Dollar Mistake". ;)

    • Alex

      Well, it _is_ part of the language. :)

      I agree that null pointers dramatically reduce the robustness of all code written using pointers (which is why I try to avoid pointers whenever possible and use references instead).

      Because you seem like the curious type, you might find this an interesting read (as a way to help guard against null-pointer madness):

  • Doug

    [quote]C (but not C++) defines a special preprocessor macro called NULL that is #defined as the value 0. Even though this is not technically part of C++, its usage is common enough that it should work in every C++ compiler:[/quote]

    This is not correct.  C++98 defines NULL in [], with a definition that's slightly different than in C ((void*)0 isn't allowed) and the definition changed in C++11 to be nullptr.

    • Alex

      Thanks for the correction. The definition of NULL is still implementation defined, and can be either 0 or nullptr. On Visual Studio 2017 and Code::Blocks 17, it's still defined as 0.

  • M_M

    I'm a little lost here so we have pointers right and you can assign NULL to them which is a macro for 0 why is that even allowed in first place when we can not assign direct adresses to it like 0x002192 (is it implemented to be accepted by the compiler?) as you said before &variable would return a fitting pointer with the address instead of the literal address?

    "C++ will implicitly convert nullptr to any pointer type. So in the above example, nullptr is implicitly converted to an integer pointer, and then the value of nullptr assigned to ptr. This has the effect of making integer pointer ptr a null pointer."

    does that mean nullptr will return a fitting type for the current pointer and that pointer has the address sex to 0x0 hence why it works for double, char and all the other types? And the compiler then just checks the address for 0x0 and converts it to true or false based on that? Thanks in advance :)

    • > NULL
      NULL is implementation defined (ie. not supported by all compilers). Don't use it.

      > why is that even allowed [assigning 0 to pointers]
      The standard says that a null pointer constant with value 0 can be assigned to any pointer. It doesn't have to be 0 after compilation (It will be 0 with most compilers).

      > we can not assign direct adresses to it like 0x002192
      0x002192 is not a null pointer constant with value 0.

      > nullptr will return a fitting type [...]
      It doesn't return anything, it's a value of type @std::nullptr_t. When assigning a value of type @std::nullptr_t to a pointer, the pointer will be turned into a null pointer.
      A null pointer value evaluated to false. How this is done is implementation defined.

  • Haider

    Should I use 'nullptr' in C++14?

  • Peter Baum

    These sentences are confusing to me:

    "C++ will implicitly convert nullptr to any pointer type.  So in the above example, nullptr is implicitly converted to an integer pointer, and then the value of nullptr (0) assigned to ptr."

    1. It isn't clear to me exactly what "integer pointer" means.  Addresses, after all, are integer values.  Pointers have a context associated with them: they are integer values that are to be used as addresses.  Is an “integer pointer” just a pointer or is it a pointer without the address context and therefore just an integer?

    2. Writing nullptr{0} makes it look as though nullptr were a simple variable, hiding the issue of its other characteristics (a pointer but not a valid address value).

    3. We are told that nullptr can be converted to 0 implicitly.  After this conversion, we have to guess as to what we can do with that 0.  Can we use it exactly as we would use the literal 0?  If so, then nothing is gained over just using 0.  Apparently, some of this nullptr characteristic remains after the conversion to 0, but we are not told exactly what this means in practice.

    4. From the example, it appears that there is either an implicit conversion from nullptr to boolean when a boolean is needed, or there is an implicit conversion from 0 to boolean because any retained nullptr characteristics do not interfere with such conversion.  Clarification would be helpful.

    5. Perhaps the simplest solution to this issue is simply to state that there can be an implicit conversion of nullptr to false.

    • nascardriver


      This isn't about the way pointers are implemented but about the data type the pointer is pointing to.

      3/4/5. Quoting the C++ Standard Draft N4659
      "A value of type std::nullptr_t can be converted to an integral
      type; the conversion has the same meaning and validity as a conversion of (void*)0 to the integral type." - § 8.2.10 4
      "For direct-initialization (11.6), a prvalue of type std::nullptr_t can
      be converted to a prvalue of type bool; the resulting value is false" - § 7.14 1
      I'd like to tell you more about the implementation of @nullptr and @std::nullptr_t, but I can't any. I assume @nullptr can be directly converted to an integral and bool type (std::nullptr_t -> bool, not std::nullptr_t -> int -> bool).
      I also assume that every remotely popular compiler doesn't do any conversions at run-time but rather replaces nullptr with a 0.

      • Peter Baum

        Hi nascardriver,

        If your interpretation of that section is correct about an integer pointer meaning the type the pointer is pointing to, then the section is even more confusing than I thought it was.  Maybe Alex can weigh in.  

        The rest of your comment makes sense to me except for the last part.  I have my doubts about compilers simply replacing the nullptr with 0 at run-time for two reasons.  Doing so would mean that the pointer could never access memory location 0.  Second, it would mean that if that location is protected memory, you would have to special case an address 0 access violation.  Of course, it is possible you are correct.  My assumption is that being a nullptr is identified as such in the structure that holds all the necessary information about a pointer.

        I also ran into an interesting situation where I didn't initialize a pointer to anything.  The program ran fine in debug mode but when I tried to run it in release mode, it was the linker that failed.  All this under Visual Studio.

        • nascardriver

          > I have my doubts about compilers simply replacing the nullptr with 0
          G++ does. You know assembly, get IDA and check out how VS handles nullptr.
          (nullptr is 0 with VS too, because Windows used NULL (aka. 0) before nullptr was introduced. NULL is still used in the Windows API)

          > Doing so would mean that the pointer could never access memory location 0.
          I'll change my sentence to -but rather replaces nullptr with a null pointer constant.-
          Since it's implementation specific what a null pointer constant is. Anything but 0 is ridiculous in my opinion.

          > you would have to special case an address 0 access violation
          Visual Studio has "Access violation reading location 0x00000000"
          Linux aborts with a Segmention Fault
          I don't know what Apple does, I assume it's similar.

          > I didn't initialize a pointer to anything.  The program ran fine in debug mode
          Ha! It could've continued running fine in release mode and one day it stops working when it's deployed on a customers system. That's why I initialize my variables. That pointer would've been a nullptr and the program wouldn't have worked in the first place.
          VS initializes uninitialized memory to 0xCC in debug mode. I don't know what the linker is doing here, it shouldn't care about values.

          IDA Pro

          • Peter Baum

            Thanks nascardriver.  Helpful.

            I was wrong about the problem ultimately being a linker problem.  It was really a compiler problem that then led to a linker failure (why they would call the linker after such an error is an open question).

            By the way, there was nothing wrong at all with the program that didn't initialize the pointer to an array of structures.  It was always properly initialized prior to use.  The compiler just worried about it.  Still, I agree it is best to initialize in that instance.

            There are still things I don't understand though.  The following program fails to compile in either debug or release mode because the pointer is not initialized to nullptr:

            But this one is perfectly fine in either debug or release mode:

            (You can also put the pointer p inside the function and comment out the free(p) with the same result.)

            I have yet to find an example other than a large program that will produce an error only in release mode.  Maybe the smaller programs get the issue optimized out?

            • nascardriver

              Your first program compiles without error and warnings for me. It should compile for you to. C4701 and C4703 are warnings, not errors.

              > compiler never noticed this can't execute either
              I haven't yet encountered a C++ compiler that checks if code is reachable. I guess there are too few cases in which unreachable code can be detected without a major impact on compilation speed for such a feature to be added.

              * Use @std::malloc and @std::free from <cstdlib>. A lot of functions were moved to the @std namespace to avoid name collisions.
              * @malloc and @free aren't usually used in C++. I don't think there's anything wrong with them, but I'd go for @new and @delete.

              • Peter Baum

                No, they are errors with the way I have Visual Studio Community 2017 setup.  Two errors identified:

                Error    C4703    potentially uninitialized local pointer variable 'p' used    nullptrTest    

                Error    LNK1257    code generation failed    nullptrTest        1

                • nascardriver

                  They're still warnings, you're just treating them as errors, which is a good setup.
                  The warnings are justified, because @p might be uninitialized when it's used.
                  You can disable the warnings in question if you really want to by using

                  I can't test this, I don't have VS.
                  The proper solution would be to initialize @p.

                • Peter Baum

                  In VS you can right click on the program in the solution explorer and then click on properties, then C/C++ and that gets you to the choices of how you want to treat warnings.  

                  We are in agreement about initialization.


    • Alex

      I updated the lesson a little bit based on your feedback. New phrasing as follows: "C++ will implicitly convert nullptr to any pointer type. So in the above example, nullptr is implicitly converted to an integer pointer, and then the value of nullptr assigned to ptr. This has the effect of making integer pointer ptr a null pointer."

      I removed the note about nullptr typically being 0, because it doesn't really add anything to the discussion, and technically a null pointer constant doesn't have to be 0, though I'm not aware of any cases where 0 isn't used for that purpose. The memory address 0 is almost always reserved for null pointers and is generally treated as a protected address.

      Note that nullptr won't implicitly convert to integer value 0 (you can try this yourself and your compiler should complain). It will convert to an integer pointer (or any other pointer type) pointing to null (typically memory address 0).

      • Peter Baum

        Hi Alex,

        Helpful, but

        1. Based on the confusion nascardriver and I expressed, there is still the issue of what "integer pointer" means.  I assumed that "integer" was being applied to the value of the pointer, not the type of the object the pointer was pointing to.  Nascardriver had the opposite interpretation.  If he is correct, then the fact that the target type is integer is not really relevant to the fact that the 0 being discussed is also an integer.  Thus it would be less confusing to use an example where the type being pointed to was something other than an integer, say a double.

        2. I was more interested in the conversion to boolean, since examples were given that stuck the pointer in a logical expression.

        • Alex

          1) "integer pointer" is common shorthand for "pointer to an integer" (as the value of the pointer itself is always a memory address, which is integral by nature). I'll clarify this bit of nomenclature in the intro article on pointers (since I use the term "integer pointer" there too). That said, I agree with your assertion that it would be better to use a non integral pointer for this example. I'll update the article.

          2) A pointer converts to boolean false if the pointer is null and boolean true otherwise.

  • Matt

    So, based on what we know up to this point in the tutorials, if we want to call a function without any required parameters, is it still considered safe to just do:

    If so, I guess I'm not seeing any use for these things yet.  Reading some of the comments below it sounds like it will be clearer sometime in the future.


  • Bonez

    Is that ok?

    • nascardriver

      Hi Bonez!

      Uniform initializers (The ones with curly brackets) are good practice, use them whenever you can, they assure that you’re initializing a variable with a value of the right type.

      PS: Please edit your comments instead of deleting and re-posting them, the code will be highlighted correctly after refreshing the page.

    • Alex

      Yup, and I updated the lesson to use uniform initialization for all examples.

  • Joao Miguel Machado

    Hey, I have a question :)

    Could I use this type std::nullptr to overload a function?
    For example say I want to write a function to record audio from a microcontroller or something. And I turn the device on but record no data, which could be a nullptr. Then this function that I overload does something when gets the nullptr and the other overloaded function is called when I don't feed it with the nullptr.

    I don't see how this could be better than justa making a 'if', but could this be done?

    Thanks :D

    • Alex

      Yes, like this:
      1) Overload a function using a pointer argument (of any type).
      2) Overload the same function with a std::nullptr_t argument.

      If you pass the function a valid pointer, it will match #1. If you pass in a null, #2 is a better match, so it should use that.

  • Astronoid

    Hello Alex,
    What is the difference between:


    ; and what is the mean of the second one, and thanks.

    • Alex

      The first parameter is a pointer, so the argument is passed by address.
      The second parameter is a reference to a pointer. This means the doSomething() function can change the address held by the argument passed into Ptr.

  • Joao Gueifao

    I got confused on why C++11 would define something like nullptr_t in the first place...

    Suggestion: At the section "std::nullptr_t in C++11", why not motivating its usefulness in something like overloaded methods that take a pointer as argument, which is something to be explained at a later lesson?

    By the way, thank you so much for your tutorial, it simply rocks!


    • Alex

      I don't discuss the motivations for std::nullptr_t here because I haven't talked about what an overloaded function is yet.

      But that's the primary case. Without std::nullptr_t, you can't disambiguate void somefcn(int) and void somefcn(*int) when calling somefcn(0). Is 0 an int or a null pointer?

  • alex be like


    introduction blablablablablablablabla

    some codes


    some thousand lines, 1 hour and a headache later
    rule: you won't need those. *insert troll face here*

    I love your tutorials
    you are the best.. :)

    • Alex

      Haha. If you think these programs are long, wait until you get to the comprehensive quiz for this chapter! ;)

      • J3ANP3T3R

        Question : the use of assigning nullptr to a pointer is so that we can check later if it is not pointing to anything ? or are there any other use for it ?

        • Alex

          Yes, that's right. We use nullptr as a way to say, "this pointer isn't pointing to anything right now". That way, we can determine whether the pointer is pointing to something or not via a simple if statement.

          The other (related) use for nullptr is to pass a null value into a pointer function parameter.

          • Hussain

            Amazing lessons Alex, Thanks a million ;)

            I was told that one bad use of pointers is to make pointers that point to nothing (AKA, dangling pointers). From above, I have the feeling that I was misinformed in the past!

            Would you kindly give example on uses we want to pass null value into a pointer function parameter?

            Also, is it true that null as an argument isn't as ()?

            Thanks in advance =)

            • Alex

              Let's be careful what we mean by "nothing". Null pointers and dangling pointers are not the same thing.

              A null pointer points to "nothing" (address 0). That is okay, because "nothing" is an acceptable known value that we can test for and work around.
              A dangling pointer points to a valid memory address, but not one that has been allocated for your application's use. These are he pointers that will get you in trouble, because there's no way to distinguish a dangling pointer from a valid one.

              I added an academic example of passing a nullptr to a function in the lesson. While this isn't particularly useful, it does show the mechanics. As for useful examples, we'll see some of those when we get into classes and object-oriented programming (in particular, we use a special type of function called a constructor to initialize our classes -- if our class contains a pointer and we want to initialize it to a null value, we'd pass in a null value).

              > Also, is it true that null as an argument isn’t as ()?

              null (0 or nullptr) is an explicit literal value, whereas () is an empty argument. They are definitely not the same thing -- one is an argument, one is the lack of an argument.

  • Jim

    At the beginning of this lesson you introduced a null pointer, int *ptr(0); which was changed to int *ptr = nullptr
    by C++11. I still like the former!

    Was this done since int*prt(5) and int *prt = 5 are both improper syntax. Since you can not assign a literal to a pointer variable?

    • Alex

      It was done mainly to help disambiguate whether a literal 0 was intended as an integer or null pointer. If you like the old-style, it will certainly continue to be supported.

  • Typo in the second code example:

    in 4th line, "an double" should be "a double".

  • csvan

    I believe there is an error in the last example in the section "the null pointer" here: did you not mean to dereference the pointer inside the if-condition, in order to check wether or not it points to anything? Right now it is written without a dereference operator.

    Keep coding. Use it for good :)

    • baldo

      The if (pnPtr) test to see if the pointer is null. If it is a null pointer then the address it is pointing is 0 (false). If the pointer is allocated (not null) then pnPtr points to a address != 0 (which means true).

Leave a Comment

Put all code inside code tags: [code]your code here[/code]