fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5. // your code goes here
  6. int arr[]={1,2,3,4};
  7. const int *p1 = &arr[0]; // non-const ptr to const data
  8. int const *p2 = &arr[0]; // non-const ptr to const data
  9. int* const p3 = &arr[0]; // const ptr to non-const data
  10. const int* const p4 = &arr[0]; // const ptr to const data
  11.  
  12. p1++; // ok
  13. p1[0]++; // compile error: modifying const data
  14.  
  15. p2++; // ok
  16. p2[0]++; // compile error: modifying const data
  17.  
  18. p3++; // compile error: modifying const ptr
  19. p3[0]++; // ok
  20.  
  21. p4++; // compile error: modifying const ptr
  22. p4[0]++; // compile error: modifying const data
  23.  
  24. return 0;
  25. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:13:7: error: increment of read-only location ‘* p1’
  p1[0]++; // compile error: modifying const data
       ^
prog.cpp:16:7: error: increment of read-only location ‘* p2’
  p2[0]++; // compile error: modifying const data
       ^
prog.cpp:18:4: error: increment of read-only variable ‘p3’
  p3++; // compile error: modifying const ptr
    ^
prog.cpp:21:4: error: increment of read-only variable ‘p4’
  p4++; // compile error: modifying const ptr
    ^
prog.cpp:22:7: error: increment of read-only location ‘*(const int*)p4’
  p4[0]++; // compile error: modifying const data
       ^
stdout
Standard output is empty