I still dont know what to put in for loop :(

    I still dont know what to put in the for loop

    for(int k = 0; k < voter_count; k++)
    for (int j = 0; j < candidate_count; j++)
        if (strcmp(candidates[j].name, name) == 0)
            return true;
        else if (strcmp(candidates[j].name, name) != 0)
            return false;
  • What you are implementing, which function, tell me in detail – Shahroz Ali Jul 17 at 19:01

Looking at the posted code and not sure of the full context of what you're trying to do, I'll take a run at it.

This is more of a question of what to take out, not what to put in.

The code is a for loop, implying that it will likely repeat the loop so that it traverses the array. But it will only run once, no matter what. Here's why. No matter what happens, no matter which path processing takes through the code, it is guaranteed to hit a return statement. As soon as a return statement is encountered, whether the return value is true or false, the function terminates immediately.

My best guess on fixing this is to remove the else if code block completely. It looks like if the condition is true, you want to return true and terminate the function, but if the condition is false, you want to keep looping through the array, so there shouldn't be any return statement yet. But, once the entire array has been traversed, if no match is found, only then should a return statement be executed.

Programming note: When dealing with a binary choice, i.e., something is either true or false, there's no need to retest a second time. If it isn't true, it simply must be false. That's the case here. So, instead of an else if, a simple else will suffice and will be more efficient because the second test isn't executed.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .