You must have known it already, but I can’t stop myself from showing off the interplay of const with pointers in C/C++.

Here goes the code. It’s simple.


void main() {

	int arr[]={1,2,3,4}; // data

	const int *p1 = &arr[0]; // non-const ptr to const data
	int const *p2 = &arr[0]; // non-const ptr to const data
	int* const p3 = &arr[0]; // const ptr to non-const data
	const int* const p4 = &arr[0]; // const ptr to const data

	p1++; // ok
	p1[0]++; // compile error: modifying const data

	p2++; // ok
	p2[0]++; // compile error: modifying const data

	p3++; // compile error: modifying const ptr
	p3[0]++; // ok 

	p4++; // compile error: modifying const ptr
	p4[0]++; // compile error: modifying const data

}

Now, let’s see what the g++ compiler (C++ 4.8.1) has to say about this code. You can try it yourself at http://ideone.com/AJUBcD.

prog.cpp: In function ‘int main()’:
prog.cpp:11:7: error: increment of read-only location ‘* p1’
  p1[0]++; // compile error: modifying const data
       ^
prog.cpp:14:7: error: increment of read-only location ‘* p2’
  p2[0]++; // compile error: modifying const data
       ^
prog.cpp:16:4: error: increment of read-only variable ‘p3’
  p3++; // compile error: modifying const ptr
    ^
prog.cpp:19:4: error: increment of read-only variable ‘p4’
  p4++; // compile error: modifying const ptr
    ^
prog.cpp:20:7: error: increment of read-only location ‘*(const int*)p4’
  p4[0]++; // compile error: modifying const data
       ^
Advertisements