C++ Programmer Alerts - List
(Page 3 of 4 )
Wrong Subscripting
C++ does not provide an automatic way to ensure that proper array subscripts are used. For example, the following code does not generate an error message:
int C[10];
int D[5];
D[-5] = 2;
Most compilers would assign array D immediately after array C in their activation record, so the likely effect of the preceding assignment is to modify the memory location of object C[5], instead of issuing an error message. Therefore D[-5] would be referring to the fifth element from the end of array C.
The most common subscript error is misreading the last element of an array. Both experienced and beginning programmers sometimes forget that the last element of the array has a subscript one less than the size of the array.
In part, because there is no automatic way to ensure that proper subscripts are used, programmers have turned to container classes provided in the Standard Template Library. These classes provide iterators and member functions that provide controlled access to the list elements. It is also possible to easily extend these classes so that subscripts are checked automatically.
Use the Right Delimiter
The following is the definition of a vector A of 10 int elements:
Vector<int> A(10);
However, someone can easily write:
Vector<int> A[10];
For the second case, object A is not a vector of 10 int elements, since the number 10 is inside square brackets and not curved parentheses. For this second case, object A is actually an array of size 10 whose elements are of type vector<int>. As you can see, this can cause great trouble. Always be careful when you are defining a vector.
Multiple Angled Brackets
One of the steps taken when translating a program is lexical analysis, which is where the individual elements of a program are determined. For example, when >> is encountered, many compilers will never treat these consecutive angled brackets as two distinct elements. They will group them as a single element (e.g. insertion operator). So the following statement may not compile as you expect:
vector<vector<int>> B;
That is, you may not have a two dimensional vector of int elements, since >> would be interpreted as a single element. A preferred way to define the two dimensional vector is:
vector<vector<int> > B;
There is a white space between the angled brackets, so the compiler will see the brackets as two distinct elements.
Next: Pointers and Dynamic Memory >>
More C++ Articles
More By Chrysanthus Forcha