Simple, probably easy to answer question. What is the difference between || and or in something like an if statement.
Simple examples:
#include <iostream>
int main(){
int x = 8;
if(x == 8 or 17){
std::cout << "Hello World!\n";
}
}
and
#include <iostream>
int main(){
int x = 8;
if(x == 8 || 17){
std::cout << "Hello World!\n";
}
}
These seem to work the same way for me. They both compile and they both display “Hello World!” I’ve always used || and didn’t even know about or. Do they do the same exact thing? Or is there a slight difference like using \n or endl where one acts slightly different. Sorry if this is a really simple question.
Thanks for your time.
As Luchian says, there is no semantic difference. A draft of the latest C++ standard says, in the “Keywords” section:
But there could be a difference for anyone reading your code. The
||operator for “logical or” goes back decades. The alternative representations are newer.They were introduced at least as early as the 1998 C++ standard (I don’t know if pre-ISO C++ had them). It’s at least conceivable that you might encounter a C++ compiler that doesn’t recognize them, but if so it’s going to be an old enough compiler that you’ll have other problems. C introduced similar identifiers in its 1995 amendment (but only with
#include iso646.h>).At least in C, and probably in C++, these alternate representations, along with digraphs and trigraphs, were introduced to cater to systems with character sets that don’t include all the characters that would otherwise be required for C and C++:
With the introduction of more modern character sets, particularly Unicode, such systems are increasingly rare.
But as far as I can tell, they’re rarely used in code (I don’t think I’ve ever seen any code that uses them), and some C++ programmers might not be aware of them. I believe your code will be more legible if you use
||rather thanor.And as Luchian also says,
(x == 8 || 17)doesn’t mean what you might expect from, say, English grammar. It doesn’t mean “x is equal to either 8 or 17”; it means((x == 8) || 17);17is treated as a condition by itself, not compared tox. Possibly you wanted to write(x == 8 || x == 17).