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.