web analytics

Normal Pointer, Const Pointer, Pointer Points to Constant and Const Pointer Points to Constant in C++

Options

codeling 1599 - 6654
@2015-12-22 19:59:04

The following C++ code snippet explains what are and how to use the normal pointer, const pointer, pointer points to constant and const pointer points to constant.

We can distinguish four situations relating to const, pointers and the objects to which they point:

  1. Normal pointer
  2. A pointer to a constant object
  3. A constant pointer to an object
  4. A constant pointer to a constant object

The following code is used to delcare a normal pointer which points to character string, it will be used in our example code.

char* p = "World";

 

1. Normal pointer

 A normal pointer of type char* be initialized with a string constant or a pointer delcared previously.

char* p1  = "Hello";  // non-const pointer,
                      // non-const data

p1 = p; //You can point to a different address

p1[0] = 'J'; //You can change its target's value

 

2. Pointer points to a constant

In the second situation, a pointer to a constant object, the object pointed to cannot be modified, but we can set the pointer to point to something else:

const char* p2 = "Hello";  // non-const pointer,
                           // const data

p2 = p; //OK, you can point to a different constant

p2[0] = 'J'; //Error! you can't change its target, because it is a constant

 

3. Const pointer

In the third situation, a constant pointer to an object, the address stored in the pointer can't be changed, but the object pointed to can be:

char* const p3 = "Hello"; // const pointer,
                          // non-const data

//A const pointer is a pointer that is constant itself. It doesn't imply that what the pointer refers to is constant.

p3 = p; //Error! You can't point to a different address, once the const pointer is declared

p3[0] = 'J'; //OK, you can change its target's value

 

4. Const pointer points to a constant

Finally, in the fourth situation, a constant pointer to a constant object, both the pointer and the object pointed to have been defined as constant and, therefore, neither can be changed:

const char* const p4 = "Hello"; // const pointer,
                                // const data
   
p4 = p; //Error! You can't point to a different address, once the const pointer is declared

p4[0] = 'J'; //Error! you can't change its target's value, because it is a constant

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com