Why are variable not recognised from inside for-statements?

91 views Asked by At

What I am trying to do is create an array that pulls even numbers from another array. I'm not sure if I have gone about it the right way. I've look for ways of returning from statements like you would functions/methods and I can't find anything, not even sure if it is possible.

Anyway, the issue I am having here is the 'return evenArray' below 'cannot find symbol.' I am not sure what this means?

public static int[] getEvenArray(int[] array)
{        
    int dividedBy = 2;
    int evenElement;
    int evenCount = 0;

    for(int i = 0; i < array.length; i++)
    {
        int[] evenArray;
        evenElement = array[i] % dividedBy;

        if(evenElement == 0)
        {
            evenCount++;
        }
        else
        {
            array[i] = 0;
        }

        evenArray = new int[evenCount];

        for(int x = 0; x < evenArray.length; x++)
        {
            if(array[i] != 0)
            {
                evenArray[x] = array[i];
            }
        }
    }

    return evenArray;
}

This is for a tutorial from one of my lectures, it's a little bit challenging to say the least :-)0

2

There are 2 answers

4
Bathsheba On

evenArray is defined within the scope of the for loop. (Actually a little worse than that; you're redeclaring it on each iteration so discarding the previous contents).

So once you're outside the for loop you can't refer to it.

Quickest fix is to use a std::vector<int> for this type, and declare it at the start of the function. Also change the return type of the function to the same. Don't forget to size the vector appropriately.

(Moving on, a smart lecturer will ask you about returning a std::vector which could potentially take a deep copy of that vector. Pre C++11 you'd mention return value optimisation, now you can talk about r-value references. No deep copy will be taken since the move constructor will be used).

0
Ali Kazmi On

Variable declared inside a block is not visible outside of it; move this int[] evenArray; to very start of function.