0

On problem set 3, I've defined a function like so:

bool vote(string name)

{

    for (int i = 0; i < candidate_count; i++)
    {
        if ((int) name == (int) candidates[i].name)
        {
            candidates[i].votes = candidates[i].votes + 1;
            return 0;
        }
        else
        {
            return 1;
        }

    }
}

Candidate Count and other arrays and variables are defined in other places so I think that's fine. It seems that the error is telling me that it might get to the end of the function and not return anything, but I don't understand why that's the case.

I'd really appreciate any help.

1

The compiler looks at code and tries to decide if there's a way that a function can complete without returning a value. In this case, it's decided that this can happen. It has found such a possibility. If candidate_count were 0, the for loop would not execute, therefore no return statement would execute.

To fix it, insert an absolute return statement at the bottom that would return the result you'd want if there were an error or failure to get a desired result. I assume that's 1?

You have an additional problem here. The for loop will only ever execute once. Turns out that you can fix both problems with essentially the same solutiion. I'll let you figure out how and why. ;-)

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

| improve this answer | |
  • Thanks Cliff, really appreciate it mate. I've changed my code a bit to address the errors you pointed out. Now I'm stuck with a similar but different issue: if I put the return false in the if... else... bit I get the same compiler error as the first time. If I put an return false outside the if bit, it always returns false (even if it should return true based on the input and what's inside the if bit). Can you help me see what I'm doing wrong? – Rafe May 10 at 15:37
  • Can you please add the new code as an edit to the question? Leave the original code so people can see what the original problem was - add the new code at the bottom. Also, cut and paste the compile message. – Cliff B May 10 at 16:21

You must log in to answer this question.

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