lundi 2 août 2021

Local variable initialization behavior C++

this piece of code:

int findsmallerNumber(int low, int high, string *str)
{
    int counter = 0;
    cout<<counter<<" ";
    string ss = *str;

    for(int i = low + 1; i <= high; i++)
    {
        if(ss[i] < ss[low])
            counter++;
    }
    return counter;
}

produces the correct output as:

4 4 3 1 1 0

but when the counter variable isn't initialized as such:

int counter;

the output obtained is:

4 8 11 12 13 13

Can someone please explain this behavior?

Aucun commentaire:

Enregistrer un commentaire