(Reader Level : Beginner)
(Knowledge assumptions : Pointers, typedef, std::vector...)
Sometimes we create our own types using the typedef keyword in C++. For eg;
typedef std::vector<int> INTVECTOR;
If we write : const INTVECTOR myVector;
It is the same as : const std::vector<int> myVector;
This means that the type (in this case, a vector of ints) itself is constant and we can't do stuff like this:
myVector.push_back(10);
Let's look at a typedef for a pointer.
typedef int* INTPTR
If we write : const INTPTR pInt;
Is it equivalent to writing? : const int* pInt;
To answer that we need to think about what these two statements syntactically mean.
In the former statement, we are saying that the type (in this case, the integer pointer) itself is constant and that we can't change it in anyway. That statement prevents us from doing stuff like this: pInt++;
In the second statement, we are informing the compiler that the value that the pointer "points" to is constant.
That means we CAN do : pInt++;
But we can't do : *pInt = 20;
In other words,
const INTPTR pInt; is equivalent to int* const pInt;
No comments:
Post a Comment