const
Using const
with pointers has some subtle aspects (pointers always seem to have subtle aspects), so let’s take a closer look. You can use the const
keyword two different ways with pointers. The first way is to make a pointer point to a constant object, and that prevents you from using the pointer to change the pointed-to value. The second way is to make the pointer itself constant, and that prevents you from changing where the pointer points. Now for the details.
First, let’s declare a pointer pt
that points to a constant:
int age = 39;
const int * pt = &age;
This declaration states that pt
points to a const int
(39
, in this case). Therefore, you can’t use pt
to change that value. In other words, the value *pt
is const
and cannot be modified:
*pt += 1; // INVALID because pt points to a const int
cin >> *pt; // INVALID for the same reason
Now for a subtle point. This declaration for pt
doesn’t necessarily mean that the value it points to is really a constant; it just means the value is a constant insofar as pt
is concerned. For example, pt
points to age
, and age
is not const
. You can change the value of age
directly by using the age
variable, but you can’t change the value indirectly via the pt
pointer:
*pt = 20; // INVALID because pt points to a const int
age = 20; // VALID because age is not declared to be const
Previous examples have assigned the address of a regular variable to a regular pointer. This example assigns the address of a regular variable to a pointer-to-const
. That leaves two other possibilities: assigning the address of a const
variable to a pointer-to-const
and assigning the address of a const
to a regular pointer. Are they both possible? The first is, and the second isn’t:
const float g_earth = 9.80;
const float * pe = &g_earth; // VALID
const float g_moon = 1.63;
float * pm = &g_moon; // INVALID
For the first case, you can use neither g_earth
nor pe
to change the value 9.80
. C++ doesn’t allow the second case for a simple reason: If you can assign the address of g_moon
to pm
, then you can cheat and use pm
to alter the value of g_moon
. That makes a mockery of g_moon
’s const
status, so C++ prohibits you from assigning the address of a const
to a non-const
pointer. (If you are really desperate, you can use a type cast to override the restriction; see Chapter 15, “Friends, Exceptions, and More,” for a discussion of the const_cast
operator.)
The situation becomes a bit more complex if you have pointers to pointers. As you saw earlier, assigning a non-const
pointer to a const
pointer is okay, provided that you’re dealing with just one level of indirection:
int age = 39; // age++ is a valid operation
int * pd = &age; // *pd = 41 is a valid operation
const int * pt = pd; // *pt = 42 is an invalid operation
But pointer assignments that mix const
and non-const
in this manner are no longer safe when you go to two levels of indirection. If mixing const
and non-const
were allowed, you could do something like this:
const int **pp2;
int *p1;
const int n = 13;
pp2 = &p1; // not allowed, but suppose it were
*pp2 = &n; // valid, both const, but sets p1 to point at n
*p1 = 10; // valid, but changes const n
Here the code assigns a non-const
address (&pl
) to a const
pointer (pp2
), and that allows pl
to be used to alter const
data. So the rule that you can assign a non-const
address or pointer to a const
pointer works only if there is just one level of indirection—for example, if the pointer points to a fundamental data type.
You can assign the address of either const
data or non-const
data to a pointer-to-const
, provided that the data type is not itself a pointer, but you can assign the address of non-const
data only to a non-const
pointer.
Suppose you have an array of const
data:
const int months[12] = {31,28,31,30,31,30, 31, 31,30,31,30,31};
The prohibition against assigning the address of a constant array means that you cannot pass the array name as an argument to a function by using a non-constant formal argument:
int sum(int arr[], int n); // should have been const int arr[]
...
int j = sum(months, 12); // not allowed
This function call attempts to assign a const
pointer (months
) to a non-const
pointer (arr
), and the compiler disallows the function call.
For yet another subtle point, consider the following declarations:
int age = 39;
const int * pt = &age;
The const
in the second declaration only prevents you from changing the value to which pt
points, which is 39
. It doesn’t prevent you from changing the value of pt
itself. That is, you can assign a new address to pt
:
int sage = 80;
pt = &sage; // okay to point to another location
But you still can’t use pt
to change the value to which it points (now 80
).
The second way to use const
makes it impossible to change the value of the pointer itself:
int sloth = 3;
const int * ps = &sloth; // a pointer to const int
int * const finger = &sloth; // a const pointer to int
Note that the last declaration has repositioned the keyword const
. This form of declaration constrains finger
to point only to sloth
. However, it allows you to use finger
to alter the value of sloth
. The middle declaration does not allow you to use ps
to alter the value of sloth
, but it permits you to have ps
point to another location. In short, finger
and *ps
are both const
, and *finger
and ps
are not const
(see Figure 7.5).
If you like, you can declare a const
pointer to a const
object:
double trouble = 2.0E30;
const double * const stick = &trouble;
Here stick
can point only to trouble
, and stick
cannot be used to change the value of trouble
. In short, both stick
and *stick
are const
.
Typically you use the pointer-to-const
form to protect data when you pass pointers as function arguments. For example, recall the show_array()
prototype from Listing 7.5:
void show_array(const double ar[], int n);
Using const
in this declaration means that show_array()
cannot alter the values in any array that is passed to it. This technique works as long as there is just one level of indirection. Here, for example, the array elements are a fundamental type. But if they were pointers or pointers-to-pointers, you wouldn’t use const
.
To write a function that has a two-dimensional array as an argument, you need to remember that the name of an array is treated as its address, so the corresponding formal parameter is a pointer, just as for one-dimensional arrays. The tricky part is declaring the pointer correctly. Suppose, for example, that you start with this code:
int data[3][4] = {{1,2,3,4}, {9,8,7,6}, {2,4,6,8}};
int total = sum(data, 3);
What should the prototype for sum()
look like? And why does the function pass the number of rows (3
) as an argument and not also the number of columns (4
)?
Well, data
is the name of an array with three elements. The first element is, itself, an array of four int
values. Thus, the type of data
is pointer-to-array-of-four-int
, so an appropriate prototype would be this:
int sum(int (*ar2)[4], int size);
The parentheses are needed because the following declaration would declare an array of four pointers-to-int
instead of a single pointer-to-array-of-four-int
, and a function parameter cannot be an array:
int *ar2[4]
Here’s an alternative format that means exactly the same thing as this first prototype, but, perhaps, is easier to read:
int sum(int ar2[][4], int size);
Either prototype states that ar2
is a pointer, not an array. Also note that the pointer type specifically says it points to an array of four int
s. Thus, the pointer type specifies the number of columns, which is why the number of columns is not passed as a separate function argument.
Because the pointer type specifies the number of columns, the sum()
function only works with arrays with four columns. But the number of rows is specified by the variable size, so sum()
can work with a varying number of rows:
int a[100][4];
int b[6][4];
...
int total1 = sum(a, 100); // sum all of a
int total2 = sum(b, 6); // sum all of b
int total3 = sum(a, 10); // sum first 10 rows of a
int total4 = sum(a+10, 20); // sum next 20 rows of a
Given that the parameter ar2
is a pointer to an array, how do you use it in the function definition? The simplest way is to use ar2
as if it were the name of a two-dimensional array. Here’s a possible function definition:
int sum(int ar2[][4], int size)
{
int total = 0;
for (int r = 0; r < size; r++)
for (int c = 0; c < 4; c++)
total += ar2[r][c];
return total;
}
Again, note that the number of rows is whatever is passed to the size
parameter, but the number of columns is fixed at four, both in the parameter declaration for ar2
and in the inner for
loop.
Here’s why you can use array notation. Because ar2
points to the first element (element 0) of an array whose elements are array-of-four-int
, the expression ar2 + r
points to element number r
. Therefore ar2[r]
is element number r
. That element is itself an array-of-four-int
, so ar2[r]
is the name of that array-of-four-int
. Applying a subscript to an array name gives an array element, so ar2[r][c]
is an element of the array-of-four-int
, hence is a single int
value. The pointer ar2
has to be dereferenced twice to get to the data. The simplest way is to use brackets twice, as in ar2[r][c]
. But it is possible, if ungainly, to use the *
operator twice:
ar2[r][c] == *(*(ar2 + r) + c) // same thing
To understand this, you can work out the meaning of the subexpressions from the inside out:
ar2 // pointer to first row of an array of 4 int
ar2 + r // pointer to row r (an array of 4 int)
*(ar2 + r) // row r (an array of 4 int, hence the name of an array,
// thus a pointer to the first int in the row, i.e., ar2[r]
*(ar2 +r) + c // pointer int number c in row r, i.e., ar2[r] + c
*(*(ar2 + r) + c // value of int number c in row r, i.e. ar2[r][c]
Incidentally, the code for sum()
doesn’t use const
in declaring the parameter ar2
because that technique is for pointers to fundamental types, and ar2
is a pointer to a pointer.
Recall that a C-style string consists of a series of characters terminated by the null character. Much of what you’ve learned about designing array functions applies to string functions, too. For example, passing a string as an argument means passing an address, and you can use const
to protect a string argument from being altered. But there are a few special twists to strings that we’ll unravel now.
3.129.194.123