I just took a practice test for a midterm exam I have tomorrow. My teacher has been very persistent about getting this one statement through my head, "There are no short cuts in C++." Meaning that whenever you create a function or if statement it must be complete in its form. For example if(statement == 1 || statement == 2). However, I just took a test that said, this was legal: if (response == 'n'||'y'). Could somebody clarify how that it a legal statement? I'm really confused on the issue.
All (?) built-in types are freely convertible to bool. (response == 'n'||'y') is an expression equivalent to (response == 'n'||true).
You could even write (response == ('n'||'y')) which is (response == (true||true)) which is (response == true) which is (response == (char)1).
- the statement is legal -- meaning that it will compile without error
- the statement is wrong -- because it is illogical, and won't do what the programmer wanted.
The "shortcut" was that the programmer was trying to express
if response is 'n' or 'y'
but even in English, that is short for
if response is 'n' or response is 'y'
or if response is one of ('n' and 'y')
Computers don't like weird stuff like that, and want you to be exact: