Search code examples
cif-statementscanf

If statement defaults to true


This is a simple process I wrote to try and fix a problem I'm having with other code. Can someone tell me why the if statements are defaulting to true? I read something about scanf requiring a space before the variable, but I did that.

#include <stdio.h>
#include <stdlib.h>

int main(){

char answer;

printf("Y or N ");

scanf(" %c", &answer);

if(answer == 'Y' || 'y'){
   printf("you said yes \n");
}

else if (answer == 'N' || 'n'){
   printf("you said no \n");
}

else {
   printf("sorry, fail \n");
}

return 0;

}

It doesn't matter whether I type N or n or any other character or even number, it spits back "you said yes".


Solution

  • The issue is with the test logic.

    if(answer == 'Y' || 'y')
    

    That statement is not working like you might think. The 'y' is netting your program a value of "true" for a lack of a better way of stating it.

    What you most likely want is a comparative test like this:

    if((answer == 'Y') || (answer =='y'))
    

    Noting that correction, following is a refactored version of your program.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    
        char answer;
    
        printf("Y or N ");
    
        if (scanf("%c", &answer) != 1)
            return 1;
    
        if((answer == 'Y') || (answer =='y'))
        {
            printf("you said yes \n");
        }
    
        else if ((answer == 'N') || (answer == 'n'))
        {
            printf("you said no \n");
        }
    
        else
        {
            printf("sorry, fail \n");
        }
    
        return 0;
    
    }
    

    Following were some tests at the terminal.

    craig@Vera:~/C_Programs/Console/ScanTest/bin/Release$ ./ScanTest 
    Y or N U
    sorry, fail 
    craig@Vera:~/C_Programs/Console/ScanTest/bin/Release$ ./ScanTest 
    Y or N Y
    you said yes 
    craig@Vera:~/C_Programs/Console/ScanTest/bin/Release$ ./ScanTest 
    Y or N N
    you said no 
    

    To recap, be aware of how logical "and" and "or" operators work within the various tests ("if", "while", and so forth).