user4290866
user4290866

Reputation:

Strange behavior with null pointers

I have stumbled upon the following problem, if I compile (using Visual Studio 2010)

int main()
{
    double* d_ptr = int(0);
    if(d_ptr == nullptr)
         cout << "I am a nullptr" << endl;

    return 0;
}

I get the result "I am a nullptr"

This also works if I substitute the pointer assignment with:

double* ptr = (int) 0;

I would have expected both to fail since they both explicitly cast to integer which has not a pointer type. Could someone help me in understanding what is going on?

EDIT: Tried again with g++ and worked. Do not know what I did wrong the first time. Now I am only still troubled why it works in the first place.

Upvotes: 1

Views: 121

Answers (2)

You have wandered into one of the murkier areas of C++ (and C). Quoting from n4296 (which is the latest freely available draft of C++14):

4.10 Pointer conversions [conv.ptr]

1 A null pointer constant is an integer literal (2.13.2) with value zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type

I am slightly surprised that (int)0 is accepted as "an integer literal" - in fact, I think that is a bug in the compiler (but it is very much a corner case).

Ah-ha! I have just remembered: Older versions of C and C++ didn't say "integer literal", they said "integer constant expression". int(0) is an integer constant expression, so it is allowed on older compilers.

This means your problem with g++ could depend on whether you specified C++14 or an earlier version.

Upvotes: 4

Arnav Borborah
Arnav Borborah

Reputation: 11789

By assigning the value of 0, to the pointer, you are setting it to null, so it is a nullptr. To make the pointer have the value of 0, do this:

double * dbl = new double{0};

Upvotes: 0

Related Questions