Search code examples
c++pointersnullnullptr

Why is there no warning or error when initializing a const pointer to null?


This might be a very basic question, but I tried to find the answer in SO and couldn't find the exact answer to it.

What's the point of initializing a const pointer with nullptr?

int *const pi = nullptr;

Why does the compiler not emit a warning or error, seeing how pointer pi can't be used effectively anywhere in the program?

I have tried compiling this with g++ -w.

Also, Can you give some use case where a const pointer will get initialized to nullptr for a valid purpose in real code?


Solution

  • Although I agree that initializing a const pointer to nullptr isn't generally especially useful, one situation where it may me appropriate is where you would conditionally define the const pi pointer to either nullptr or some other (valid) address, depending on a compile-time setting, like in the following example. (The const qualifier prevents other code from inadvertently changing the value and, thusly, breaking the aforementioned compile-time condition.)

    #include<iostream>  
    
    #define USENULL 1 // Comment out this line to get a 'valid' pointer!
    
    int main()
    {
        int a = 42;
        #ifdef USENULL
        int* const pi = nullptr;
        #else
        int* const pi = &a;
        #endif
        int* pa = pi;
        if (pa) std::cout << *pa;
        else std::cout << "null pointer";
        std::cout << std::endl;
        return 0;
    }
    

    Such a situation could arise when you need to differentiate between debug and release builds, for example.