A Strange Bug in Iteration (print value != return value).

The following is my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int test(vector<int> input, int ind){
    if (input[ind]!=5) {
        ind++;
        test(input, ind);
    }
    else {
        cout<<"---test2 ind="<<ind<<endl;
        return ind;
    }
}

int main(int argc, const char * argv[]) {
    vector<int> input=vector<int> {1,2,3,4,5};
    int ind=0;
    cout<<"result="<<test(input, ind)<<endl;
}

The output is:
---test2 ind=4
result=0

However, I expect 'result=4'.
You see that the 'cout' value is Different as 'return' value, although print is just followed by return.
Could anyone explain where is wrong?

If I change the 'test' function to be:
1
2
3
4
5
6
7
8
9
void test(vector<int> input, int& ind){
    if (input[ind]!=5) {
        test(input, ++ind);
    }
    else {
        cout<<"---test2 ind="<<ind<<endl;
        return;
    }
}

It is working.
I am just wondering why the first one does not work, what is wrong there??
Last edited on
The problem is this:
In function 'int test(std::vector<int>, int)': 15:1: warning: control reaches end of non-void function [-Wreturn-type]


You return ind in the case you found the value (line 8), after that it is dissmissed. You need to return ind; in any case (move line 8 after line 9). On line 4 you need to assign the result to ind.
Change lines 3 and 4 to return test(input, ind+1);
Last edited on
Thanks all. dhayden's solution is working.
Thank you!
Topic archived. No new replies allowed.