1: //pointers7.cpp 3: #include <iostream> 4: using namespace std; 6: int main() 7: { 8: cout << "\nThis program illustrates the use of const with pointers."; 9: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 11: cout << "\nThere are four scenarios to illustrate, depending on " 12: "whether the entity\nrequired to be constant is the pointer, " 13: "or the pointee, or both, or neither.\nThe program will require " 14: "a certain mount of comment activation/de-acitvation\nand " 15: "re-building to verify all of the stated claims."; 16: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 18: ////Case 1 19: ////Not using const means both pointer and pointee can change 20: //int i = 1; 21: //int j = 2; 22: //int * p = &i; 23: //p = &j; //OK (the pointer value can be altered) 24: //*p = 6; //OK (the value pointed to can also be altered) 26: ////Case 2 27: ////Illustrates when pointer can change but pointee can't 28: //int i = 1; 29: //int j = 2; 30: //const int * p = &i; 31: //int const * p = &i; //This line is equivalent to the one above. 32: //p = &j; //OK (the pointer value can be altered) 33: //*p = 6; //not OK (the value pointed to cannot be altered) 35: ////Case 3 36: ////Illustrates when pointee can change but pointer can't 37: //int i = 1; 38: //int j = 2; 39: //int * const p = &i; 40: //p = &j; //not OK (the pointer value cannot be altered) 41: //*p = 6; //OK (the value pointed to can be altered) 43: ////Case 4 44: ////Illustrates when neither pointer nor pointee can change 45: //int i = 1; 46: //int j = 2; 47: //const int * const p = &i; 48: //p = &j; //not OK (the pointer value cannot be altered) 49: //*p = 6; //not OK (the value pointed to also cannot be altered) 52: ////Illustrates that "const" can appear on either side of type name, 53: ////not only with pointer types but with "ordinary" types as well. 54: //const int i = 5; 55: //int const j = 6; 56: //cout << i << j << endl; 57: }