How is "int* ptr = int()" value initialization not illegal?

C++Visual C++PointersInitializationBuilt in-Types

C++ Problem Overview


The following code (taken from here):

int* ptr = int();

compiles in Visual C++ and value-initializes the pointer.

How is that possible? I mean int() yields an object of type int and I can't assign an int to a pointer.

How is the code above not illegal?

C++ Solutions


Solution 1 - C++

int() is a constant expression with a value of 0, so it's a valid way of producing a null pointer constant. Ultimately, it's just a slightly different way of saying int *ptr = NULL;

Solution 2 - C++

Because int() yields 0, which is interchangeable with NULL. NULL itself is defined as 0, unlike C's NULL which is (void *) 0.

Note that this would be an error:

int* ptr = int(5);

and this will still work:

int* ptr = int(0);

0 is a special constant value and as such it can be treated as a pointer value. Constant expressions that yield 0, such as 1 - 1 are as well allowed as null-pointer constants.

Solution 3 - C++

The expression int() evaluates to a constant default-initialized integer, which is the value 0. That value is special: it is used to initialize a pointer to the NULL state.

Solution 4 - C++

From n3290 (C++03 uses similar text), 4.10 Pointer conversions [conv.ptr] paragraph 1 (the emphasis is mine):

> 1 A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to 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 and is distinguishable from every other value of object pointer or function pointer type. Such a conversion is called a null pointer conversion. [...]

int() is such an integral constant expression prvalue of integer type that evaluates to zero (that's a mouthful!), and thus can be used to initialize a pointer type. As you can see, 0 is not the only integral expression that is special cased.

Solution 5 - C++

Well int isn't an object.

I beleive what's happening here is you're telling the int* to point to some memory address determined by int()

so if int() creates 0, int* will point to memory address 0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsharptoothView Question on Stackoverflow
Solution 1 - C++Jerry CoffinView Answer on Stackoverflow
Solution 2 - C++Blagovest BuyuklievView Answer on Stackoverflow
Solution 3 - C++Mark RansomView Answer on Stackoverflow
Solution 4 - C++Luc DantonView Answer on Stackoverflow
Solution 5 - C++MegatronView Answer on Stackoverflow