March 24, 2007
Watch those brackets!
I've been teaching C++ in an industrial setting recently, and happened to notice a particularly subtle pitfall.
Suppose we write
vector<int> v(10);
Then we've defined a vector named v with 10 elements. But old habits die hard, and sometimes we might be tempted to write
vector<int> v[10];
Note the square brackets in place of the parentheses.
What we've done here is to say that we want an array with 10 elements, each of which is an empty vector! And of course, v[i] is still meaningful--it's just that its meanine is now completely different.
Needless to say, the diagnostic messages that result from this particular mistake are likely to be hard to interpret, as they will probably point to a place far away from the actual source of the problem.
One more reason to avoid stating vector sizes explicitly. Let's hear it for push_back!
Posted by Andrew Koenig at 02:40 PM Permalink
|