How do I make a function that takes two integers and returns a Boolean value?

2

I want to do a function that takes two integers and returns a boolean , but when I put the:

return (encontrou);

It gets an error on top of the encontrou variable. Here is part of my function:

public static bool verificar(int cont, int m1, int m2, int[] Cobertura1, int[] Cobertura2)
{
        bool encontrou;

        for (int i = 0; i <= cont; i++)
        {
            if ((m1 == Cobertura1[i]) & 
                (m2 == Cobertura2[i]) & 
                (m1 == Cobertura2[i]) & 
                (m2 == Cobertura1[i]))
            {
                encontrou = false;
            }
            else
                encontrou = true;
        }

        return (encontrou);
    }
    
asked by anonymous 01.11.2017 / 03:33

2 answers

5

The error you get is due to the lack of initialization of the encontrou variable. Assign a value when declaring it:

public static bool verificar(int cont, int m1, int m2, int[] Cobertura1, int[] Cobertura2)
{
    bool encontrou = false; //agora começa a false
    ...

The reason for the error is because there is no guarantee that for runs, so there is no guarantee that you have true or false in the variable. And the compiler does not allow you to use a local variable, in this case in return , without having previously assigned a value.

Often times you can structure it differently so you do not have this problem. In your code you are also using & which is and binary when you should be using && which is and logical.

    
01.11.2017 / 04:04
4

Now understanding the question better, the code did not even compile and it is necessary to initialize the variable before using it.

But I have other comments.

I think I wanted to use && and used & which in some situations can produce a different result . Something like this:

public static bool verificar(int cont, int m1, int m2, int[] Cobertura1, int[] Cobertura2) {
    bool encontrou;
    for (int i = 0; i <= cont; i++) encontrou = !(m1 == Cobertura1[i] && m2 == Cobertura2[i] && m1 == Cobertura2[i] && m2 == Cobertura1[i]);
    return encontrou;
}

On the other hand you might want this:

public static bool verificar(int cont, int m1, int m2, int[] Cobertura1, int[] Cobertura2) {
    for (int i = 0; i <= cont; i++) if (!(m1 == Cobertura1[i] && m2 == Cobertura2[i] && m1 == Cobertura2[i] && m2 == Cobertura1[i])) return true;
    return false;
}

You can reverse the condition to eliminate the negation operator. I do not know if I should have this denial, or if the whole condition should be this.

The original algorithm seems strange, it goes changing state to each different pass, I think it is working by coincidence, depending on the state of the vectors can give unexpected result. But I can not say without a larger context.

    
01.11.2017 / 05:52