Ok, so im reading the C++ Primer, Fifth Editon and im learning about constexpr for the first time. It starts by saying:
It is important to understand that when we define a pointer in a constexpr declaration, the constexpr specifier applies to the pointer, not the type to which the pointer points:
const int *p = nullptr; // p is a pointer to a const *q = nullptr; // q is a const pointer to int Ok so i think to myself... Well it p is a pointer to a const then it means that p(the pointer) it-self is not a constant so i may change it. So ofcourse, i tried it out on my IDE:
#include <iostream> #include <list> #include <vector> #include <string> int main() { const int x = 0; const int y = 30; const int *p = x; *p = &y; return 0; } Guess what. It gave me a error when i try to assign *p to the adress of constant y. Well the error specifically
error: assignment of read-only location '* p'| Wow i was suprised. I Really thought the book said p is a pointer to a const. SO i thought p is not a constant it self, so you can change it.? Or is my anaolgy wrong??
And then ofcourse it tells me:
constexpr int *q = nullptr; // q is a const pointer to int Well if my previous anaology was correct then, this pointer is an actual const it-self. So it may not be changed..? Or am i still wrong?
Constexpr
Ok guys so i understood. I shouldnt derefrence when i assign pointers to "objects" or anything. But now i get this error when i try out constexpr for the first time!
error: invalid conversion from 'const int*' to 'int*' [-fpermissive]| And this is my code:
int main() { const int a = 0; const int i = 5; constexpr int *w = &a; return 0; }
const int *p = &x;And of course you cannot assign*p, because the resultingintis const! (Not to mention that you're attempting to assign anconst intto aconst int*)