'Pointer and Const'

Write your question here
- Hi While I am studying 'Pointer' part I am stuck again. This is from this website. Once we declare 'const int', we can't modify the pointer's value which in this example is [10,20,30]. But output are 11,21,31.

How can it be like that? Would somebody can explian this? I am sorry to bother you again. but I got headache. Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  // pointers as arguments:
#include <iostream>
using namespace std;

void increment_all (int* start, int* stop)
{
  int * current = start;
  while (current != stop) {
    ++(*current);  // increment value pointed
    ++current;     // increment pointer
  }
}

void print_all (const int* start, const int* stop)
{
  const int * current = start;
  while (current != stop) {
    cout << *current << '\n';
    ++current;     // increment pointer
  }
}

int main ()
{
  int numbers[] = {10,20,30};
  increment_all (numbers,numbers+3);
  print_all (numbers,numbers+3);
  return 0;
} 

1
2
3
4
5
6
7
8
void increment_all (int* start, int* stop)
{
  int * current = start;
  while (current != stop) {
    ++(*current);  // increment value pointed
    ++current;     // increment pointer
  }
}


Here is where 10,20,30 changes to 11,20,30. And they are not const here. So they can be changed.

1
2
3
4
5
6
7
8
void print_all (const int* start, const int* stop)
{
  const int * current = start;
  while (current != stop) {
    cout << *current << '\n';
    ++current;     // increment pointer
  }
}


Here they are const, and are not being modified, they are simply being printed out.

Edit: Read below for a more detailed explanation.
Last edited on
When you do something like this:

const int *p1 = variable

You can't modify the value it points to. So this will not work:

*p1 = 5;

The print_all function is actually increasing the memory location that the "current" pointer is pointing to, not the value.
â””germanchocolate
â””TarikNeaj

Thank you for both of you guys. I am international student in UNLV so I have to figure English and C++ out myself. I have thought about this code again then as you told me I realized number changed due to 'Increment_all' function not because of 'Print_all' function. Thank you again.
I may bother you few more time from now on :)
As long as you use Code tags and ask understandable and specific questions, feel free to bother us as much as you want, glad I could help :)
Glad we could help. That's what this forum is here for, so don't hesitate to ask us fellow programmers for our help. :D
Topic archived. No new replies allowed.