Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for Explanation of pointer initializing to const int and int

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.

like image 877
Pogomogo Avatar asked Nov 24 '20 18:11

Pogomogo


1 Answers

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;
like image 182
Bathsheba Avatar answered Oct 06 '22 00:10

Bathsheba