Why is this code "disgusting"?

In the book PPP2, there's a "Try this" exercise that says:
Why are we so disgusted with that use of v ? Give at least three ways this
could lead to obscure errors. List three applications in which you’d particu-
larly hate to find such code.
, and the code it's referring to is as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
double v_val; // the value to which larger_than_v() compares its argument
bool larger_than_v(double x) { return x>v_val; }

void f(list<double>& v, int x)
{
    v_val = 31; // set v_val to 31 for the next call of larger_than_v
    auto p = find_if(v.begin(), v.end(), larger_than_v);
    if (p!=v.end()) { /* we found a value > 31 */ }

    v_val = x; // set v_val to x for the next call of larger_than_v
    auto q = find_if(v.begin(), v.end(), larger_than_v);
    if (q!=v.end()) { /* we found a value > x */ }
    // . . .
}


And right below that code (and above the "Try this") it says:
Yuck! We are convinced that people who write such code will eventually get what
they deserve, but we pity their users and anyone who gets to maintain their code.
Again: there has to be a better way!


What I'm thinking is that because v is also the name of the vector, it could cause confusion if it's also used to mean "value" (although the value is named v_val). So it could cause maintainability and obscurity issues because of that. But if that's one, then what are the other two? And I also can't think of any specific kinds of applications this would be a problem in.

So I was wondering if someone would help me out a bit here. Maybe giving me a little hint. Thanks in advance.
Last edited on
it's mainly about passing a global variable to an algorithm as a hidden parameter. A mutable global variable, to boot. Note the next chapter explains how to avoid this
Oh, okay. I didn't think of that. It makes sense if it's a global variable. Thanks.
Last edited on
v is not very descriptive. If I saw code like that I'd just delete it and save the world !
Same for void f and int x.
Topic archived. No new replies allowed.