Pointers/Memory Allocation   «Prev  Next»
Lesson 3 Creating const pointer arguments to functions
Objective Examine use of keyword const to create pointer arguments

Creating const pointer Arguments to Functions

const pointer Arguments Declaration

const type * identifier

declares the identifier as a pointer whose pointed at value is constant. This construct is used when pointer arguments to functions will not have their contents modified.
void fcn(const int* p){
  // within here it is illegal
  // to have  *p = expression;

This provides "const safety" allowing the compiler to detect an error. It also allows the compiler to optimize how these arguments are passed.

Non-const pointers

Let us contrast this with a non-const pointer argument:
void fcn(int* p){
 // within here it is legal
 // to have  *p = expression;

Now attempting to pass a const pointer value will lead to a syntax error.
const int size = 100;  //size may not be modified
fcn(&size);  //illegal because the address
  // of a const variable is being passed to an
  // argument that allows for modification
  // of what is pointed at.

Declaring a pointer constant

We can take this one step further. The form
const type* const identifier
declares the identifier as a
pointer constant.


Here are some other examples of const variable declaration.

C++ How to Program