Pointers and const

Hello, I am a bit confused with these couple lines of code:

1
2
3
constexpr int null2 = 0;
  int *p5 = null2;
  cout << *p5 << " " << null2;


Gives me the error:
error: invalid conversion from 'int' to 'int*' [-fpermissive]


now this,
1
2
3
const int null1 = 0;
  int *p1 = null1;
  cout << *p1 << " " << null1;


Gives me the same error:
error: invalid conversion from 'int' to 'int*' [-fpermissive]


I tried 2 fixes, by adding the &operator to the very right object:

1
2
3
const int null1 = 0;
  int *p1 = &null1;
  cout << *p1 << " " << null1;


Gives the error:
error: invalid conversion from 'const int*' to 'int*' [fpermissive


Tried this and ONLY this worked:

1
2
3
const int null1 = 0;
  const int *p1 = &null1;
  cout << *p1 << " " << null1;


I tried doin the same fixes for the first code in the topic and it didn't work.

Anyone got an explanation ? ^_^
Last edited on
What behavior do you expect and why?
The compiler explained why the first three code fragments aren't permitted in C++: integers are not convertible to pointers and pointers to const are not convertible to pointers to non-const.

Existing implicit conversions for pointers are documented, for example, here: http://en.cppreference.com/w/cpp/language/implicit_conversion#Pointer_conversions and http://en.cppreference.com/w/cpp/language/implicit_conversion#Qualification_conversions
Last edited on
Topic archived. No new replies allowed.