Pratham Shah
Pratham Shah

Reputation: 168

Weird behavior of min

typedef long long ll;

ll maxtokens(vector<ll>::iterator beg, vector<ll>::iterator end)
{
    ll min, j = 0, n = end - beg;
    if(n == 1) 
        return *beg;

    for(int i = 1, min = *beg; i < n; i++)
    {
        ll t = *(beg + i);
        if(min > t)
        {
            min = t;
            j = i;
        }
        // cout << min << " " << (*(beg + i)) << endl;
    }
        // cout << min << " " << j << endl;

    if(j == 0)
        return n*min;

    for(int i = 0; i < j; i++)
        *(beg + i) -= min;

    return maxtokens(beg, beg + j) + n*min;
}

This here is a function for a question in codechef. What I found weird is value of min so I used a debugger to see value of min at each step and found that value of min is as expected inside of the loop but as soon as it exits the for loop value stored inside of min changes to a garbage value.This bug is removed if i write min=*beg before the for loop. I couldn't understand why value of min changed by itself.

ll stands for long long int

Can you tell me where I did anything wrong?

I didn't knew which tag to use so I just used c++ please tell me which other tags I should have used for future references.

Though I don't think this would be of any help but question is available here https://www.codechef.com/LRNDSA02/problems/STUPMACH

Thanks in advance.

Upvotes: 0

Views: 86

Answers (1)

cigien
cigien

Reputation: 60218

You are shadowing the variable min in the loop. In this snippet

int min = 1;
for (int i = 0, min = 5; i < n; ++i)  // this declares a new 'min'
  // ...

The min in the for loop is different than the one outside. So any changes to the min inside the loop won't affect the min outside the loop.

Note that in an expression like

int i = 0, min = 5;

both i and min are new variables.

The simpler approach in this case would be to use an algorithm, like this:

int min = *std::min_element(beg, end);

which avoids having to write a loop at all.

Upvotes: 5

Related Questions