forked from wadehuber/codeexamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstintptr.cpp
More file actions
41 lines (34 loc) · 1.62 KB
/
Copy pathconstintptr.cpp
File metadata and controls
41 lines (34 loc) · 1.62 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
#include<iostream>
using namespace std;
int main() {
int num = 0; // ptr1, ptr2, ptr3 will be initialized with &num
int num1 = 10;
int num2 = 42;
const int * ptr1 = # // pointer to constant int
int const * ptr2 = # // pointer to constant int
int * const ptr3 = # // constant int pointer
cout << "Initial values:" << endl;
cout << "num1=" << num1 << endl;
cout << "num2=" << num2 << endl;
cout << endl;
cout << "After assigning new address value to the pointer:";
cout << "ptr1=" << ptr1 << " *ptr1=" << *ptr1 << " &ptr1=" << &ptr1 << endl;
cout << "ptr2=" << ptr2 << " *ptr2=" << *ptr2 << " &ptr2=" << &ptr2 << endl;
cout << "ptr3=" << ptr3 << " *ptr3=" << *ptr3 << " &ptr3=" << &ptr3 << endl;
ptr1 = &num1;
ptr2 = &num2;
// ptr3 = &num1; // ERROR: Can't assign to a constant pointer
cout << endl;
cout << "ptr1=" << ptr1 << " *ptr1=" << *ptr1 << " &ptr1=" << &ptr1 << endl;
cout << "ptr2=" << ptr2 << " *ptr2=" << *ptr2 << " &ptr2=" << &ptr2 << endl;
cout << "ptr3=" << ptr3 << " *ptr3=" << *ptr3 << " &ptr3=" << &ptr3 << endl;
// *ptr1 = 1111; // ERROR: Can't modify value pointed to by ptr1
// *ptr2 = 2222; // ERROR: Can't modify value pointed to by ptr2
*ptr3 = 3333;
cout << endl;
cout << "After assigning new value to the dereferenced pointer:";
cout << "ptr1=" << ptr1 << " *ptr1=" << *ptr1 << " &ptr1=" << &ptr1 << endl;
cout << "ptr2=" << ptr2 << " *ptr2=" << *ptr2 << " &ptr2=" << &ptr2 << endl;
cout << "ptr3=" << ptr3 << " *ptr3=" << *ptr3 << " &ptr3=" << &ptr3 << endl;
return 0;
}