You shadow maxInt
by declaring another variable with the same name. See my comments here:
int maxinlst(int lst[], int size) {
// First declaration
int maxNum;
for (int i = 0; i < size; i++) {
cout << i;
if (lst[i] == lst[0])
// Second declaration
int maxNum = lst[i];
else if (maxNum < lst[i]) {
maxNum = lst[i];
}
}
return maxNum;
}
This is legal in C++, and in most languages with block scope. The second declaration creates a new variable, but it's never used because it goes out of scope immediately, so the whole assignment, along with the conditional, can be eliminated by the compiler. If you enable compiler warnings, you should get a warning about the second declaration because that variable is never used again:
test.cpp: In function ‘int maxinlst(int*, int)’:
test.cpp:8:17: error: unused variable ‘maxNum’ [-Werror=unused-variable]
int maxNum = lst[i];
^~~~~~
This also means that the value of the outer maxNum
after the first iteration of the loop is indeterminate and reading it could be undefined behavior so the second loop iteration is either going to (a) use an indeterminate value since the outer maxNum
was never assigned or (b) something else entirely because of UB.
If the second conditional is never true (assuming an indeterminate value and not UB) then the value returned by this function will also be indeterminate -- whatever unpredictable number maxNum
happened to be.
The correction here would be to remove int
in the second declaration.
You could also rewrite this to avoid the first in-loop conditional:
int maxinlst(int lst[], int size) {
// First declaration
int maxNum = lst[0];
for (int i = 1; i < size; i++) {
if (maxNum < lst[i]) {
maxNum = lst[i];
}
}
return maxNum;
}
As far as why cout << i
changes the value you see, that's exactly the nature of using indeterminate values / undefined behavior. You can't reason about what's happening. Adding or removing other code could also change the value returned by the function. You may even see different values if you run the program multiple times without making any changes to it.