0

I am trying to implement the selection sort function with the following code:

void sort(int values[], int n)
{
int temp;
for (int i = 0; i < n; i++)
{
    int min = i;
    for (int j = i+1; j < n; j++)
    {
        if (values[min] > values[j])
            min = j;
    }
    // Swap values;
    temp = values[min];
    values[j] = values[i];
    values[i] = temp;
}
}

I receive an error: helpers.c:40:16: error: use of undeclared identifier 'j' based on my use of

 values[j] = values[i];

I see that I can fix this by changing the j to min:

 values[min] = values[i];

However, I find this a little less clear. Why is there an error in the first way that I wrote it?

1

Where is j is declared?

for (int j = i+1; j < n; j++)

It can only be used within the code block ({.....}) where it is declared.

2
  • It is not sufficient to declare within the for declaration? for (int j = i+1; j < n; j++) – Haim May 7 '17 at 22:43
  • It can only be used in that for loop, and values[j] = values[i]; is outside that loop. – DinoCoderSaurus May 8 '17 at 2:19

You must log in to answer this question.

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