Ad

What Is The Difference Between For (int I = 0; I

- 1 answer

I have a code like this for question 53 of leetcode:

#include <stdio.h>

int solve(int arr[], int size)
{
    int lmax, qmax, tmp, i, j,  m = (size / 2) - 1;
    for (i = m, tmp = 0, lmax = arr[m]; i >= 0; i--)
    {
        tmp += arr[i];
        if (tmp > lmax)
        {
            lmax = tmp;
        }
        else
        {
            lmax = lmax;
        }
    }
    for (j = m + 1, tmp = 0, qmax = arr[m + 1]; j < size; j++)
    {
    
        tmp += arr[j];
        if (tmp > qmax)
        {
            qmax = tmp;
        }
        else
        {
            qmax = qmax;
        }
    }
    return lmax + qmax;
}

If i change this code block:

int lmax, qmax, tmp, i, j,  m = (size / 2) - 1;

for (j = m + 1, tmp = 0, qmax = arr[m + 1]; j < size; j++)
{
   
    tmp += arr[j];
    if (tmp > qmax)
    {
        qmax = tmp;
    }
    else
    {
        qmax = qmax;
    }
}

to this

int lmax, qmax, tmp, i, m = (size / 2) - 1;

for (int j = m + 1, tmp = 0, qmax = arr[m + 1]; j < size; j++)
{
   
    tmp += arr[j];
    if (tmp > qmax)
    {
        qmax = tmp;
    }
    else
    {
        qmax = qmax;
    }
}

which is i change to

int lmax, qmax, tmp, i, m = (size / 2) - 1; -> int lmax, qmax, tmp, i, j, m = (size / 2) - 1;

j -> int j

my output is printing diffrent results, i could not find the meaningful explanation of this, in "int j" situation i can print correct "qmax" values in scope but when i tried to do "lmax + qmax" it returns sum of addresses.

Ad

Answer

When you use the type inside the for you are creating a new variable (in your case three variables: j, tmp, and qmax). If there are other variables with the same name, they are shadowed until the loop terminates.

int solve(int arr[], int size)
{
    int lmax, qmax, tmp,i, j,  m = (size / 2) - 1;

    // qmax exists here

    for (int j = m + 1, tmp = 0, qmax = arr[m + 1]; j < size; j++)
    {
        // loop with different j, tmp, and qmax
    }

    // back to old uninitialized qmax

    return lmax + qmax; // this qmax does not have the value you "want"
}

gcc has the option -Wshadow that may help in this case.

Ad
source: stackoverflow.com
Ad