HOWTO avoid mistakes in conditional instructions

In C or C++ it's easy to made mistake in expression of conditional instruction and use assignment instead of comparison. It's presented in below snippet, where we want to check if x is equal to 6:

int main(){
    int x;

    /* first case */
    /* OK */
    if(x==6){
        /* sth */
    }
    /* WRONG */
    if(x=6){
        /* sth */
    }

    /* second case */
    /* OK */
    if(x!=6){
        /* sth */
    }
    /* WRONG */
    if(x=!6){
        /* sth */
    }

    return 0;
}

This code will be compiled successfully because its syntax is valid.

Those mistakes may be reduced by using following practice: while comparing something unmodifiable (string, number..) and variable, variable is written always on the right side. It's presented below:

int main(){
    int x;

    /* first case */
    /* OK */
    if(6==x){
        /* sth */
    }
    /* WRONG */
    if(6=x){
        /* sth */
    }

    /* second case */
    /* OK */
    if(6!=x){
        /* sth */
    }
    /* WRONG */
    if(6=!x){
        /* sth */
    }

    return 0;
}

Now conditional instructions with mistakes contain incorrect syntax and may be caught and fixed during compilation:

rgawron@foo:~$ gcc s2.c
s2.c: In function ‘main’:
s2.c:10: error: lvalue required as left operand of assignment
s2.c:20: error: lvalue required as left operand of assignment

0 commentaires:

Post a Comment