Introduction to Programming and C++

Contents Previous Topic Next Topic

If you look at Program 1 of the previous section, you will notice a property which is just waiting for a bug: the number 5 appears twice. First it appears in the array declaration, and second, in the for loop. Suppose you change one value: if you forget to change the other, you may run into problems.

Now, this may not seem to be that difficult a problem, however, suppose that the value 5 appeared in twenty locations, sometimes mixed with other instances of 5 which have nothing to do with the number of elements in this array. If you want to change the value, you must make sure that you find all instances of 5.

Perhaps, instead, you might consider assigning the value 5 to a variable, as is shown in Program 1.

Program 1. Using a variable to define the array size.

#include <iostream>

using namespace std;

int main() {
	int n = 5;
	int a[n];

	a[0] = 95;
	a[1] = 14;
	a[2] = 72;
	a[3] = 84;
	a[4] = 36;

	for ( int i = 0; i < n; ++i ) {
		cout << "The entry at index " << i << " is " << a[i] << endl;
	}

	return 0;
}

In order to better help the compiler, it is best to indicate the the integer n is constant—that is, it will not change in the life of the program, as is shown in Program 2. In C++, it is common to use variable names that are all capital letters.

Program 2. Using a constant variable.

#include <iostream>

using namespace std;

int main() {
	const int ARRAY_SIZE = 5;
	int a[ARRAY_SIZE];         // an array of ARRAY_SIZE integers

	a[0] = 95;
	a[1] = 14;
	a[2] = 72;
	a[3] = 84;
	a[4] = 36;

	for ( int i = 0; i < ARRAY_SIZE; ++i ) {
		cout << "The entry at index " << i << " is " << a[i] << endl;
	}

	return 0;
}

Now, if you want to change the array size, you need only change one variable.

More importantly, you may not want a junior programmer to accidentally modify a variable when he or she is fixing a bug. A junior developer may not understand everything the function is intended to do, and may incorrectly believe that all that needs to be changed is one value, when in fact, the problem lies elsewhere.

Constant Pointers to Constants

In Program 3, you may have noted that we cannot even modify the value of constant through a pointer. If you're interested in the myriad of ways of declaring pointers to be const, please visit Wikipedia.


Questions

I can't think of any useful questions... If you can think of one, let me know.


Contents Previous Topic Top Next Topic