Search code examples
cpointersif-statementshort-circuiting

What is wrong with my character comparison conditional?


I have a simple subroutine here that takes in a char array and returns a boolean value.

There is something wrong with my conditional. I tested it by passing a single character string "A", and so check_char = 97 and using short-circuit the conditional should give false for check_char != 'a'. The subroutine should return 1. But it always returns 0. Why is this? Something wrong here that I'm just not noticing?

/*
 * Checks string of characters and returns 1 if string is a valid DNA sequence and
 * returns 0 if string is not a valid DNA sequence.
 */
int is_valid_dna(char *sequence){
        int i;
        for( i = 0; i < ( sizeof(sequence) / sizeof(sequence[0]) ); i++ ){
                int check_char = tolower(sequence[i]);
                if( check_char != 'a' || check_char != 'c'   
                        || check_char != 'g' || check_char != 't' ){
                        return 0;
                }
        }
        /* If the subroutine made it this far, then the sequence is a valid DNA sequence */
        return 1;
}

EDIT: Thanks everyone. Passing in the size of the array and using ANDs in the conditional worked out perfectly.


Solution

  • using short-circuit the conditional should give false for check_char != 'a'

    Yes it does, but since you're using || the short-circuit would be to abort the rest of the condition if the answer were true: we only need one of the clauses to be true to make the whole thing true, so we can stop one we've found one true. But it's false, so you continue on to check_char != 'c' which is true and so we short-circuit the rest of the condition and return 0.

    Did you mean to use && between your conditions, not ||?