C++ Why is my comparison between int and str.length() not working?

Viewed 2005

I am sending an array of names to a function that should compute length of each name and send back the largest one as number of characters. My comparison between longest and names[i].length() is never true. I initialize longest to -1 so first name should replace -1 with the length of characters in that name, however at the end of the function it return longest with my initial value of -1

#include <iostream>
#include <string>
using namespace std;

int findLongestName(string names[], int numNames);

int main() {
   string names[25] {"Bob Hope", "Steve Nice", "Mary Jane", "James Higgenbothem", "Ace Blue"};
   int numNames = 5;
   int longName;

   longName = findLongestName(names, numNames);
   cout << "Longest name is " << longName << " characters.\n";

   system("PAUSE");
   return 0;
}

int findLongestName(string names[], int numNames) {
    int longest = -1;

    for (int i = 0; i < numNames; i++) {
        if (names[i].length() > longest) {
            longest = names[i].length();
        }
    }

    return longest;
}

Can someone take a look and explain what I am doing wrong? I should/want to receive 18 back from the function for name James Higgenbothem.

2 Answers

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

Related