I was working through exercises in C++ Primer and found online solutions for Exercise 2.32.
I understood that the following code was illegal because initializing can't convert from int to int*:
int null = 0, *p = null;
However, two of the solutions that were mentioned, that I did not come up with were:
const int null3 = 0, *p3 = null3;
constexpr int null4 = 0, *p4 = null4;
How come it allows these during compile without error? I was still expecting the initialize of p3 and p4 to require the & to denote address (&null3, &null4).
Here is the code I have from my notepad file:
#include <iostream>
int main()
{
// int null = 0, *p = null; // it is not legal; depending on intent there are two ways to fix (that I can think off atm)
{
int null = 0, *p = &null; // if the goal is to point to 'null'
}
{
int null2 = 0, *p2 = 0; // if the goal is to create a nullptr
}
{
const int null3 = 0, *p3 = null3; // if the goal is to create a nullptr
}
{
constexpr int null4 = 0, *p4 = null4; // if the goal is to create a nullptr
}
return 0;
}
When I run via Microsoft Visual Studio CMDPrompt it allows me to 'cl "Exercise 2.32.cpp"' without error.
0
is one way of denoting a null pointer constant. (It's an integer type that evaluates to zero.) In other words it is a special case and you are allowed to assign a pointer type to it.
A standards compliant compiler should issue a diagnostic for the assignments of a pointer type to null3
and null4
. (It should also issue a diagnostic for int *p = +0;
.) If yours doesn't then check appropriate compiler flags are set.
Using nullptr
is far better though:
int *p = nullptr;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With