Reputation: 4465
Why am I getting this error: error: cannot initialize a variable of type 'int *const'
with an rvalue of type 'const int *
when compiling the following code?
Code:
constexpr int ch1 = 5;
constexpr int* pch1 = &ch1;
constexpr int ch2 = 5;
constexpr int* pch2 = &ch2;
cout << *pch1+*pch2;
Let me make this clear. The point of this whole ordeal is to initialise these variables at compile time. If there's a better way to do this, please let me know.
Upvotes: 1
Views: 2939
Reputation: 25388
The fact that you have declared pch1
and pch2
as constexpr
does not of itself make them const int *
, so you would need:
constexpr int ch1 = 5;
constexpr const int* pch1 = &ch1;
constexpr int ch2 = 5;
constexpr const int* pch2 = &ch2;
However, then you get:
error: '& ch1' is not a constant expression
error: '& ch2' is not a constant expression
So you're still not winning.
Edit: As chris points out, you can fix the latter problem by declaring ch1
and ch2
as static
. Their addresses then become constexpr
:
constexpr static int ch1 = 5;
constexpr const int* pch1 = &ch1;
constexpr static int ch2 = 5;
constexpr const int* pch2 = &ch2;
Upvotes: 1