Search code examples
carraysgcc-warning

Getting unused variable warning


I'm trying to make a program that takes 3 integers as input, assigns the 3 integers into an array, and outputs them in ascending order. I don't know why my program is not working and it says

unused variable 'array[]'

and I don't know why. I thought that if it goes through the if statement it would create the array in a new order (the proper ascending order). But when I run it, it just outputs the 3 integers that I input in that order.

int main(){

    int num1 = 0;
    int num2 = 0;
    int num3 = 0;

    scanf("%d %d %d", &num1, &num2, &num3);

    char array[] = {num1, num2, num3};

    int largestNum = numLarge(num1, num2, num3); //function gets largest number

    if (num3 == largestNum){

        if (num2 > num1){
            char array[] = {num1, num2, num3};
        }
        else{
            char array[] = {num2, num1, num3};
        }
    }
    else if (num2 == largestNum){

        if (num3 > num1){
            char array[] = {num1, num3, num2};
        }
        else{
            char array[] = {num3, num1, num2};
        }
    }
    else if (num1 == largestNum){

        if (num3 > num2){
            char array[] = {num2, num3, num1};
        }
        else{
            char array[] = {num3, num2, num1};
        }
    }


    printf("%d ", array[0]);
    printf("%d ", array[1]);
    printf("%d", array[2]);




    return 0;
}

Solution

  • But when I run it, it just outputs the 3 integers that I input in that order.

    Here in your code, in each and every if and else blocks you are re-creating a local array[] whose scope is within the braces {} of that particular if/else block i.e, if(condition){//scope only here} and after the end of braces you'd be left with the initial array and hence your output is always as the original order.

    How to avoid it?

    Instead of recreating the array in each if and else block, try assigning num1,num2 & num3 appropriately

    I mean instead of something like:

    if (num3 == largestNum){
    
        if (num2 > num1){
            char array[] = {num1, num2, num3};
        }
        else{
            char array[] = {num2, num1, num3};
        }
    

    do something like this:

    if (num3 == largestNum){
    
        if (num2 > num1){
             array[0] = num1; 
             array[1] = num2;
             array[2] = num3;
             //you can avoid re-assigning here as there is no change of order
        }
        else{
             array[0] = num2; 
             array[1] = num1;
             array[2] = num3;
        }