简体   繁体   中英

Why is variable initialisation redundant?

I've solved a 3*N + 1 problem (100) on UVa Online Judge but here's one thing that I don't understand, but it has something to do with Java, I guess, not with the algorithm itself. So here's the code:

private static int maxCycleLength(int lo, int hi) {
        maxLength = 0;
        int n = 0;
        int length = 0;

    for (int i = lo; i <= hi; i++) {
        // It's the first time we're computing the cycle length for n
        if (lengths[i] == 0) {
            n = i;
            length = 1;
            while (n != 1) {
                if ((n % 2) == 0) {
                    n = n >> 1;
                    length++;
                }
                else {
                    n = 3 * n + 1;
                    n = n >> 1;
                    length += 2;
                }
            }
            lengths[i] = length;
        }
        // Otherwise we just look it up
        else
            length = lengths[i];

        // Check if the current cycle length is the maximum
        if (length > maxLength)
            maxLength = length;
    }
    return maxLength;

What I don't understand: My IDE (IDEA) tells me that in this piece of code the initialisation of variables n and length is redundant, however, maxLength must be initialised and if I don't do it, it does not compile.

Why so? How is maxLength different here from n and length ?

On all code paths, you initialize n and length before you ever try and read a value from them. Regardless of what happens, the value you assign to them initially will not be used, since you'll overwrite it with something else before you need it.

maxLength though gets read from before you assign a new value to it, when you do the length > maxLength comparison, or in the return , if the for loop is skipped. Since it won't have a value on the first pass, you need to give it a starting value to use.

maxLength is different because its value is used outside the for loop. If the for loop is never entered, maxLength will never be initialized (if you remove the initialization at the start), so the return statement becomes invalid.

The other two variables ( n and length ) are guaranteed to be assigned before they are accessed, even after removing the initial initializations. They are not accessed outside the for loop, and inside the for loop, both the if and else clauses start by initializing length . n is initialized only by the if cluase, but it's only accessed within that clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM