Intent shadowing is a semantic mistake: similarly named variables represent related meanings, but code confuses them even when scopes do not hide one another. The compiler may accept the program while the wrong data is sorted, searched, or assigned. section 9.1
Sorting the clone while searching the original
A constructor clones input values into array, then calls selection_sort(values, size). The cloned array is the stored data, but the original values are sorted. Changing the call to selection_sort(array, size) aligns the operation with the intended data and fixes the behavior. section 9.1
Reduce confusion by making each variable’s meaning and ownership visible:
- Use descriptive names for copied, sorted, stored, and input data rather than relying on short names that seem obvious. section 9.1
- Distinguish global, instance, and parameter variables explicitly; use a namespace for global state and this-> for the current instance. section 9.1
- Apply changes incrementally and test behavior, especially when correcting legacy code whose surrounding assumptions are unclear. section 9.1
Listing 9.1 Identical variable names in various scopes
double rad = 1.0; #1
class Circle {
private:
double rad; #2
public:
Circle(double rad) : rad(rad) {} #3
void setRadius(double rad) { #3
if (rad < 0)
throw std::invalid_argument("negative radius");
rad = rad;
}
double sum() const {
return rad + rad; #4
}
double getRadius() { return rad; } #5
};
int main() {
Circle c(3);
std::cout << "radius is " << c.getRadius() << '\n';
std::cout << "enlarged radius is " << c.sum() << '\n';
return 0;
}
Compare identical names across global, class, parameter, and method contexts to see why apparent meaning becomes difficult to trace. section 9.1
