C++ Why is my comparison between int and str.length() not working?
The issue is with the data type names[i].length()
returns an unsigned int
. Comparing -1
with names[i].length()
will always give you a false
.
int findLongestName(string names[], int numNames) {
unsigned int longest = 0;
for (int i = 0; i < numNames; i++) {
if (names[i].length() > longest) {
longest = names[i].length();
}
}
return longest;
}
when comparing a signed value longest
with unsigned value names[i].length()
, the compiler converts the signed value into an unsigned
value, which makes int longest
which is initially -1
, a very big unsigned number 4294967295
So, essentially, this always evaluates to false:
if (names[i].length() > longest)
Fixes:
You can typecast the unsigned int returned from string.length() into int
if ((int)names[i].length() > longest) {
or make longest an unsigned int from the start