Ad

Strcmp() Doesn't Seem To Work When Used As A Condition In A "for" Loop - C Language

I tried to write a function that has as an input a string called name as well as other inputs ( irrelevent for the purpose of this question). One of the things required is to do "something" after checking if name (input of function) corresponds to one of the names already stored in an array called candidates (already populated earlier in the main program). The problem is, when using strcmp() as a condition inside the for loop as shown in the following code below, the function doesn't seem to work :

bool vote(int rank, string name, int ranks[])
{
    // TODO
    for (int c = 0; c < candidate_count && strcmp(candidates[c], name) == 0 ; c++)
    {
            ranks[rank] = c;
            return true;       
    }
    return false;
}

However, It seems to work just fine when used as condition in an "If" statement within the for loop's brackets, as shown in the following code :

bool vote(int rank, string name, int ranks[])
{
    // TODO
    for (int c = 0; c < candidate_count; c++)
    {
        if ((strcmp(candidates[c], name)) == 0)
        {
            ranks[rank] = c;
            return true;
        }        
    }
    return false;
}

I am having trouble finding the difference between the two versions of the code. Could you please identify the cause of the problem ? Thanks in advance !

Ad

Answer

The bottom version of the code is checking if any candidate matches the name.

The top version checks if the first candidate matches the name. If it matches, it goes inside the loop and returns true. If it doesn't match, the condition of the for loop is not satisfied so the loop exits and false is returned.

Ad
source: stackoverflow.com
Ad