Assuming option
is of type char
, you can replace
if (option == 'y' || option == 'Y')
by
if (tolower((unsigned char)option) == 'y')
The cast to unsigned char
is necessary. tolower
takes an argument of type int
whose value must be either within the range of unsigned char
or equal to EOF
(which is typically -1
). If plain char
happens to be signed (which is common) and if the value of option
happens to be negative (which could happen if the input is unusual), then tolower(option)
would have undefined behavior.
(Yes, the need for a cast is annoying and counterintuitive. Yes, tolower()
should accept any argument within the range of char
. Yes, you still have to deal with it.)
Other possibilities:
option = tolower((unsigned char)option);
if (option == 'y') ...
or
switch (option) {
case 'y': case 'Y': ...
...
}
The switch
solution still tests against both 'y'
and 'Y'
, but it's less verbose; you don't have to mention option
more than once. And of course you can also switch
on tolower((unsigned char)option)
.