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:
Furthermore, the alternative representations shown in Table 5 for
certain operators and punctuators (2.6) are reserved and shall not be
used otherwise:
and and_eq bitand bitor compl not
not_eq or or_eq xor xor_eq
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 than or.
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); 17 is treated as a condition by itself, not compared to x. Possibly you wanted to write (x == 8 || x == 17).
It's the exact same, it's an alternative operator. You can find a full list here.
Also, note that x == 8 or 17 returns true always. It doesn't check whether x is either 8 or 17.
There is no difference between them,both of them do the same thing
Related
Here is a very simple C++ application I made with QtCreator :
int main(int argc, char *argv[])
{
int a = 1;
int b = 2;
if (a < 1 or b > 3)
{
return 1;
}
return 0;
}
To me, this is not valid C++, as the keyword or is not a reserved keyword.
But if I compile and run it, it works fine without any warnings ! The exit code is 0 and if I change b = 4, the exit code is 1 !
I'm not including anything to make sure there is no hidden define.
This is really strange to me. Is this something Qt is defining ? I didn't find anything in the documentation regarding that.
According to Wikipedia:
C++ defines keywords to act as aliases
for a number of symbols that function
as operators: and (&&), bitand (&),
and_eq (&=), or (||), bitor (|), or_eq
(|=), xor (^), xor_eq (^=), not (!),
not_eq (!=), compl (~).
As MadKeithV points out, these replacements came from C's iso646.h, and were included in ISO C++ as operator keywords. The Wikipedia article for iso646.h says that the reason for these keywords was indeed for international and other non-QWERTY keyboards that might not have had easy access to the symbols.
or is a C++ keyword, and you're allowed to use it instead of ||. There is no magic.
The same goes for and and most other logical operators. It's generally best to stick to the commonly known names though, to avoid confusion like this. If you use or, someone will wonder "why does this compile" ;)
iso646.h defines a number of operator alternatives - it's part of the C++ standard.
I have a habit of using the following syntax in my compile-time flags:
#if (defined(A) & defined(B))
It's usually suggested that I do it with the && as follows:
#if (defined(A) && defined(B))
I know the difference between the two operators, and that in normal code && would short-circuit. However, the above is all handled by the compiler. Does it even matter what I use? Does it affect compile time by some infinitesimal amount because it doesn't evaluate the second define()?
Since defined(SOMETHING) yields 0 or 1, so that you're guaranteed 0 or 1 on both sides, it doesn't make a technical difference whether you use & or &&.
It's mostly about good habits (using & could carry over to some situation where it would be wrong) and about writing code that is easy to grasp by simple pattern matching. A & in there causes a millisecond pause while one considers whether it possibly could be a bit-level thing.
On the third hand, you can't use keyword and, which you ¹can use in ordinary C++ code.
Notes:
¹ With Visual C++ you can use and via a forced include of <iso646.h>.
According to the C99 standard, the expressions used in the preprocessor are constant expressions as defined by the C language itself, and are evaluated using the same engine. Therefore, && is a logical and operator that short circuits based on its LHS, and & is a bitwise operator with no predefined order of evaluation.
In practical terms, when used with defined() as you are, there is no difference between the two. However, the following would show a difference:
#define A 2
#define B 5
#if (A && B)
printf("A && B\n");
#endif
#if (A & B)
printf("A & B"\n);
#endif
In this case, A && B will be output, but not A & B (since the result of that bitwise-and is 0)
I would like to add to the previous answers that it can actually matter a lot in a situation like this:
#define A 0
#define B 21
#if (A != 0) && (42 / A == B)
/* ... */
#endif
Here, if A == 0, the compiler will not break. Writing (A != 0) & (42 / A == B) will make the compiler complain about a division by zero.
I've recently (only on SO actually) run into uses of the C/C++ comma operator. From what I can tell, it creates a sequence point on the line between the left and right hand side operators so that you have a predictable (defined) order of evaluation.
I'm a little confused about why this would be provided in the language as it seems like a patch that can be applied to code that shouldn't work in the first place. I find it hard to imagine a place it could be used that wasn't overly complex (and in need of refactoring).
Can someone explain the purpose of this language feature and where it may be used in real code (within reason), if ever?
It can be useful in the condition of while() loops:
while (update_thing(&foo), foo != 0) {
/* ... */
}
This avoids having to duplicate the update_thing() line while still maintaining the exit condition within the while() controlling expression, where you expect to find it. It also plays nicely with continue;.
It's also useful in writing complex macros that evaluate to a value.
The comma operator just separates expressions, so you can do multiple things instead of just one where only a single expression is required. It lets you do things like
(x) (y)
for (int i = 0, j = 0; ...; ++i, ++j)
Note that x is not the comma operator but y is.
You really don't have to think about it. It has some more arcane uses, but I don't believe they're ever absolutely necessary, so they're just curiosities.
Within for loop constructs it can make sense. Though I generally find them harder to read in this instance.
It's also really handy for angering your coworkers and people on SO.
bool guess() {
return true, false;
}
Playing Devil's Advocate, it might be reasonable to reverse the question:
Is it good practice to always use the semi-colon terminator?
Some points:
Replacing most semi-colons with commas would immediately make the structure of most C and C++ code clearer, and would eliminate some common errors.
This is more in the flavor of functional programming as opposed to imperative.
Javascript's 'automatic semicolon insertion' is one of its controversial syntactic features.
Whether this practice would increase 'common errors' is unknown, because nobody does this.
But of course if you did do this, you would likely annoy your fellow programmers, and become a pariah on SO.
Edit: See AndreyT's excellent 2009 answer to Uses of C comma operator. And Joel 2008 also talks a bit about the two parallel syntactic categories in C#/C/C++.
As a simple example, the structure of while (foo) a, b, c; is clear, but while (foo) a; b; c; is misleading in the absence of indentation or braces, or both.
Edit #2: As AndreyT states:
[The] C language (as well as C++) is historically a mix of two completely different programming styles, which one can refer to as "statement programming" and "expression programming".
But his assertion that "in practice statement programming produces much more readable code" [emphasis added] is patently false. Using his example, in your opinion, which of the following two lines is more readable?
a = rand(), ++a, b = rand(), c = a + b / 2, d = a < c - 5 ? a : b;
a = rand(); ++a; b = rand(); c = a + b / 2; if (a < c - 5) d = a; else d = b;
Answer: They are both unreadable. It is the white space which gives the readability--hurray for Python!. The first is shorter. But the semi-colon version does have more pixels of black space, or green space if you have a Hazeltine terminal--which may be the real issue here?
Everyone is saying that it is often used in a for loop, and that's true. However, I find it's more useful in the condition statement of the for loop. For example:
for (int x; x=get_x(), x!=sentinel; )
{
// use x
}
Rewriting this without the comma operator would require doing at least one of a few things that I'm not entirely comfortable with, such as declaring x outside the scope where it's used, or special casing the first call to get_x().
I'm also plotting ways I can utilize it with C++11 constexpr functions, since I guess they can only consist of single statements.
I think the only common example is the for loop:
for (int i = 0, j = 3; i < 10 ; ++i, ++j)
As mentioned in the c-faq:
Once in a while, you find yourself in a situation in which C expects a
single expression, but you have two things you want to say. The most
common (and in fact the only common) example is in a for loop,
specifically the first and third controlling expressions.
The only reasonable use I can think of is in the for construct
for (int count=0, bit=1; count<10; count=count+1, bit=bit<<1)
{
...
}
as it allows increment of multiple variables at the same time, still keeping the for construct structure (easy to read and understand for a trained eye).
In other cases I agree it's sort of a bad hack...
I also use the comma operator to glue together related operations:
void superclass::insert(item i) {
add(i), numInQ++, numLeft--;
}
The comma operator is useful for putting sequence in places where you can't insert a block of code. As pointed out this is handy in writing compact and readable loops. Additionally, it is useful in macro definitions. The following macro increments the number of warnings and if a boolean variable is set will also show the warning.
#define WARN if (++nwarnings, show_warnings) std::cerr
So that you may write (example 1):
if (warning_condition)
WARN << "some warning message.\n";
The comma operator is effectively a poor mans lambda function.
Though posted a few months after C++11 was ratified, I don't see any answers here pertaining to constexpr functions. This answer to a not-entirely-related question references a discussion on the comma operator and its usefulness in constant expressions, where the new constexpr keyword was mentioned specifically.
While C++14 did relax some of the restrictions on constexpr functions, it's still useful to note that the comma operator can grant you predictably ordered operations within a constexpr function, such as (from the aforementioned discussion):
template<typename T>
constexpr T my_array<T>::at(size_type n)
{
return (n < size() || throw "n too large"), (*this)[n];
}
Or even something like:
constexpr MyConstexprObject& operator+=(int value)
{
return (m_value += value), *this;
}
Whether this is useful is entirely up to the implementation, but these are just two quick examples of how the comma operator might be applied in a constexpr function.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to check for equals? (0 == i) or (i == 0)
Why does one often see “null != variable” instead of “variable != null” in C#?
Why do some experienced programmers write expressions this way?
What is the meaning of NULL != value in C++?
For example,
int k =5;
if( 5 == k )
{
}
is preferred over
if (k == 5)
{
}
Is it considered only for formatting purpose or is there any reason behind it?
Because that form makes it harder to introduce a bug by forgetting one of the equals signs. Imagine if you did this:
if (k = 5)
This was intended as a comparison, but it's now an assignment! What's worse, it is legal, and it will mess up your program in multiple ways (the value of k is changed, and the conditional always evaluates to true).
Contrast this with
if (5 = k)
This is not legal (you cannot assign to a literal) so the compiler will immediately flag it as an error.
That said, this style of writing code (assignments within conditionals) is not as prevalent today as it once was. Most modern compilers will flag this as a warning, so it's unlikely to go undetected. Personally I don't like the second form and since the compiler is there to help I don't use it.
If you mistype and write
if (k = 5) // instead of ==
then you likely just introduced a hard to find bug. (Actually, it used to be hard to find. Nowadays, most compilers will flag this as a warning.)
This, however, will result in a compile-time error
if (5 = k)
BTW, this style is called Yoda Conditions :-)
It's to avoid the mistake of
if( k = 5 ) {
}
which would always equal true.
A. Who said it's preferred ?!
the only reason i can think of it's to avoid:
int k =5;
if( 5 = k )//notice one "="
{
}
like this you will get a compilation error, while the other way will work. but I think it's less readable and less preferred.
First of all, most people prefer the second form, since it feels "more natural"; the first form is felt as "reversed", and in fact is often called "Yoda conditional".
The rationale behind using the first form is to avoid accidental assignment when typing = instead of == by error. Since in a conditional you can write any expression, = is allowed, so in case of mistyping the instruction
if(k = 5)
{
}
won't check if k is equal to 5, but will assign 5 to k and, since = returns a reference to its left hand operator, the condition will be evaluated as true and the if body will always be executed.
On the other hand, if you typed = instead of == in the Yoda conditional you would get
if(5 = k)
{
}
which results in a compilation error, since you can't assign anything to a literal (5).
Although they look like a good idea, "Yoda conditionals" are quite weird looking, and, most importantly, almost any good compiler with warnings turned on will warn you anyway if you write an assignment inside a conditional expression, so most people just use the "natural looking" form.
It's because a common typo is typing = instead of ==.
Here is a very simple C++ application I made with QtCreator :
int main(int argc, char *argv[])
{
int a = 1;
int b = 2;
if (a < 1 or b > 3)
{
return 1;
}
return 0;
}
To me, this is not valid C++, as the keyword or is not a reserved keyword.
But if I compile and run it, it works fine without any warnings ! The exit code is 0 and if I change b = 4, the exit code is 1 !
I'm not including anything to make sure there is no hidden define.
This is really strange to me. Is this something Qt is defining ? I didn't find anything in the documentation regarding that.
According to Wikipedia:
C++ defines keywords to act as aliases
for a number of symbols that function
as operators: and (&&), bitand (&),
and_eq (&=), or (||), bitor (|), or_eq
(|=), xor (^), xor_eq (^=), not (!),
not_eq (!=), compl (~).
As MadKeithV points out, these replacements came from C's iso646.h, and were included in ISO C++ as operator keywords. The Wikipedia article for iso646.h says that the reason for these keywords was indeed for international and other non-QWERTY keyboards that might not have had easy access to the symbols.
or is a C++ keyword, and you're allowed to use it instead of ||. There is no magic.
The same goes for and and most other logical operators. It's generally best to stick to the commonly known names though, to avoid confusion like this. If you use or, someone will wonder "why does this compile" ;)
iso646.h defines a number of operator alternatives - it's part of the C++ standard.