Search code examples
c++cif-statementparentheses

else if & curly brackets


Why do these two code snippets have different outputs ?

The only difference between them is the curly brackets around each if/else-if statement, but that shouldn't matter here, right?

while (1){
    if (i>=n&&j<0)
        break;

    else if (j<0)
        if (Arr[i])
            c++;

    else if (i>=n)
        if(Arr[j])
            c++;

    else if (Arr[i]==1&&Arr[j]==1)
        c+=2;

    i++;
    j--;
}

..

while (1){
    if (i>=n&&j<0){
        break;
    }
    else if (j<0){
        if (Arr[i])
            c++;
    }
    else if (i>=n){
        if(Arr[j])
            c++;
    }
    else if (Arr[i]==1&&Arr[j]==1){
        c+=2;
    }
    i++;
    j--;
} 

Solution

  • If you format correctly the first code snippet

    while (1){
        if (i>=n&&j<0)
            break;
    
        else if (j<0)
            if (Arr[i])
                c++;
    
            else if (i>=n)
                if(Arr[j])
                    c++;
                else if (Arr[i]==1&&Arr[j]==1)
                    c+=2;
    
        i++;
        j--;
    }
    

    then it is seen that else or else if correspond to the closest if statement.