I ran into an interesting line of code today. I did not know it was legal to use the word “or”. I thought there was only ||.
What is this called and where can I read more about it?
Thanks
if (V_discount == "y" or "Y" or "Yes" or "yes")
{
cout << "Your discount is: ";
}
edit: It turns out the if statement doesn’t do much. I put a cout<<“hi”; in the brackets, and it executes regardless of what V_discount has in it.
I thought it was called something because netbeans is highlighting “or” in blue.
2nd edit:
v == "y" || "Y"
is not the same as
v == "y" || v == "Y"
Only the latter functions “as intended”. “As intended” being checking whether v is the string “y” or v is the string “Y”.
It’s called an “alternative token”, documented in section 2.6 [lex.digraph] of the current ISO C++ standard, and in section 2.5 of the 1998 ISO C++ standard. (This is the same section that defines “digraphs”, such as
<%for{and%:for#.)But the code you’ve shown uses it incorrectly.
First, if
xwere anint, then you’d probably want this:rather than this:
The latter is actually legal, but it means something quite different.
And comparing strings for equality is not straightforward. If
V_discountis achar*orchar[], then comparingV_discount == "yes"compares pointer values, not the contents of the strings, and they’ll certainly compare unequal. IfV_discountis astd::string, then I think it will work — but you still have to compare it to each of the literals individually. Otherwise, as Tony Delroy’s answer says, it compiles but does something entirely unexpected involving implicit conversions tobool.