The following code snippets are from a C program.
The user enters Y or N.
char *answer = '\0';
scanf (" %c", answer);
if (*answer == ('Y' || 'y'))
// do work
I can't figure out why this if
statement doesn't evaluate to true.
I checked for the y or n input with a printf
and it is there, so I know I'm getting the user input. Also when I replace the the condition of the if statement with 1 (making it true), it evaluates properly.
For a start, your answer
variable should be of type char
, not char*
.
As for the if
statement:
if (answer == ('Y' || 'y'))
This is first evaluating 'Y' || 'y'
which, in Boolean logic (and for ASCII) is true since both of them are "true" (non-zero). In other words, you'd only get the if
statement to fire if you'd somehow entered CTRLA (again, for ASCII, and where a true values equates to 1)*a.
You could use the more correct:
if ((answer == 'Y') || (answer == 'y'))
but you really should be using:
if (toupper(answer) == 'Y')
since that's the more portable way to achieve the same end.
*a You may be wondering why I'm putting in all sorts of conditionals for my statements. While the vast majority of C implementations use ASCII and certain known values, it's not necessarily mandated by the ISO standards. I know for a fact that at least one compiler still uses EBCDIC so I don't like making unwarranted assumptions.
answer
shouldn't be a pointer, the intent is obviously to hold a character. scanf
takes the address of this character, so it should be called as
char answer;
scanf(" %c", &answer);
Next, your "or" statement is formed incorrectly.
if (answer == 'Y' || answer == 'y')
What you wrote originally asks to compare answer
with the result of 'Y' || 'y'
, which I'm guessing isn't quite what you wanted to do.
Because comparison doesn't work that way. 'Y' || 'y'
is a logical-or operator; it returns 1
(true) if either of its arguments is true. Since 'Y'
and 'y'
are both true, you're comparing *answer
with 1.
What you want is if(*answer == 'Y' || *answer == 'y')
or perhaps:
switch (*answer) {
case 'Y':
case 'y':
/* Code for Y */
break;
default:
/* Code for anything else */
}
Source: Stackoverflow.com