I have the following code:
#include <iostream>
using std::cout;
using std::endl;
void display(const int* start, const int* end);
int main()
{
int numbers[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
display(numbers, numbers + 9);
system("pause");
return 0;
}
void display(const int* start, const int* end)
{
const int* ptr;
for (ptr = start; ptr != end; ptr++)
{
cout << *ptr << endl;
}
}
The output is correct and works as I expected to work.
But in the display function, I have specifically mentioned that my "ptr" variable is a constant which means that the value of the "ptr" variable cannot change and hence, it will only refer to one address at all times.
Looking at the for loop, I am able to increment the ptr variable (Why?).
So, out of curiosity I removed the const keyword from const int* ptr
line to see what happens and it gives me the following error:
for (ptr = start; ptr != end; ptr++) // a value of type "const int*" cannot be assigned to an entity of type "int *"
{
cout << *ptr << endl;
}
The error is for ptr = start;
That gave me new questions:
- My ptr variable after modifications is NOT a const int* so why is it saying that it is a const int *?
- I am assigning my start variable (const int ) to a ptr variable (const int ), but it thinks that I am trying to assign my start variable of type int to a const int which is the ptr variable?
- Even if this does not work, then why does incrementing work when my ptr was constant before?
I looked at the following two links to understand it further but it does not answer my question:
1. Why this Error: a value of type "const int*" cannot be assigned to an entity of type "int*"?
2. How pointer increment works
EDIT
The reason why my question is not the duplicate of this link (1. Why this Error: a value of type "const int*" cannot be assigned to an entity of type "int*"?) is because this is what he is assigning a constant pointer's value to another pointer which is also pointing to another non constant value and hence why. In my case I initialized a constant integer pointer and I am still able to increment it. I do not think that we can increment constant variables?