Why if( constant == variable ) is preferred instead of if ( variable == constant ) [duplicate] - c++

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 ==.

Related

Ternary Operator Not Generating Error

I've been familiar with the ternary operator for quite some time now, and have worked with it in a few differnet languages. My understanding of the operator is this:
condition ? expr1 : expr2
However, in C++, the following code is legal:
int i = 45;
(i > 0) ? i-- : 1;
Aren't you, in effect, just writing 1; or i - 1;How is this a complete statement? I understand that the intention of the code is to decrement i if it's greater than 0, but I would've thought that the code would generate a compiler error as just being an expression, not a full statement. I expected code like this:
int i = 45;
i = (i > 0) ? i - 1 : i;
This is called expression statement. The expression is evaluated and its value is discarded.
Even this is valid:
42;
although it does nothing. Only side effects (like i--, assignment, etc) in the expression have effects.
In fact, many statements we use are expression statements: assignments, function calls, etc:
a = 42;
foo();
That is a valid expression. You might have received a warning because you are not saving the result of the expression, but that you have the i-- your statement does have an effect.
In C++, an expression like 1 is a perfectly valid statement with no side effects. You could very feasibly write this function:
void f() {
1;
}
In fact, even this is correct.
void f() {
;;;;
}
A literal statement evaluates its arguments but does nothing more. The system views 1; as being just like func();. The only difference is that while func(); would logically have some side effects, 1; does not so it ends up being a no-op. The ternary operator evaluates like an if-statement, so the second form is only evaluated if the operand is true. Thus:
(i > 0) ? i-- : 1;
If i is greater than 0, the second form is evaluated. When it is evaluated, it carries its side effect, which decrements i by 1. Otherwise, the third form is evaluated, which does nothing. Although this block of code works, it is not incredibly readable, so while it's nice toy code a real if-statement is ideal for situations like this. For the same reason, this line would have the same effect but be frowned upon for being equally unreadable.
((i > 0) && (i--)) || 1;
Assuming you didn't overwrite the boolean operators, this code will short-circuit and behave like the ternary operator. If i is not greater than 0, then the && need not evaluate its second operand since the && is false, but the || must since it might be true. Inversely, if i is greater than 0, the && needs to evaluate but the || already knows it's true.
Aren't you, in effect, just writing 1; or i - 1;
No: i-- is not the same as i - 1. In the first case, the value of i is modified. In the second case it is not.
In the event that i less than or equal to zero, then you're correct that the resulting 'code' will be 1. However, the compiler will realise that this is not a useful thing to execute and so it ought to generate code equivalent to:
if( i > 0 ) i--;
Some (including myself) would consider that using the ternary operator in this fashion is bad style. Just for fun, here's another way someone might write it that's also not very nice (also more likely to generate compiler warning):
i > 0 && i--;
In the end, style is a matter of preference. The compiler, for the most part, will decide the best way to turn your code into assembly. So you owe it to yourself to write code that is clear and concise.

What's the point of the NOT operator? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Currently checking out C++ using this tutorial. It explains what the ! NOT operator is, kind of, but I don't think I fully understand why I'd ever want to use it. Can someone please explain?
The ! operator is useful if you want to check that a condition is not currently satisfied.
Imagine a function that tells you if a particular subsystem of your application was initialized and another function to initialize it:
bool subsystem_is_initialized();
void subsystem_initialize();
You could check that it was initialized and initialize it if it wasn't using the not operator.
if (!subsystem_is_initialized())
subsystem_initialize();
For all practical purposes, it's a shorter way to compare a value to zero, with an explicit suggestion that the affected value is boolean. You don't absolutely need it, but then again, neither do you need multiplications (you can loop over an addition), additions (you can do it with binary logic), or most of binary logic (you can do pretty much anything with NANDs, I've been told, but I haven't researched it myself).
Also keep in mind that, like almost all other C++ operators, it can be overloaded by classes.
A language is not always (in fact as good as never) defined to have the minimal set of features but a set of features that useful. For example, if you had the following code:
if (!test_something())
do_something();
You could also express this as
if (test_something()) {
} else
do_something();
but it would be less easy to read. So, while logical negation can usually be expressed by other constructs of the C++ language, it helps readability to express negation explicitly to indicate your intent.
It's used when you need to flip a true/false in a condition, to increase readability.
e.g.
Compare
// Ensure that the thing is NOT red.
if (thing_is_red() == false)
...
if (!thing_is_red())
...
Okay, you want to divide the sum of two numbers to a third one, so you can do this if the third number is not zero.
#include <iostream>
using namespace std;
int main()
{
int a,b,c,sum;
cin >> a >> b >> c;
sum = a+b;
if (c!=0) //which is equivalent to if(!c)
cout << sum/c;
}
I used an easy example in order to understand it quickly. Is everything okay now? Regards and good luck with your study.
! or the NOT operator is the logical equivalent of a NOT gate.
So, a NOT gate truth table says if x is true, then !x is false. and vice-versa.
Not too difficult if you think of it logically. For example NOT of male is a female, NOT true is false, NOT simple is complex..
The most frequent case is probably with an std::istream:
int i;
std::cin >> i;
if ( ! std::cin ) {
// Something went wrong...
}
Other than that, all sorts of classes have isValid() or
isDone() functions; to iterate using a GoF iterator, for
example:
for ( IteratorType i( init ); ! i.isDone(); i.next() ) {
// Do something with i.element()
}
Map classes often have a contains function, so you might ask
if ( ! myMap.contains( key ) )
You'll also use boolean variables from time to time: for
a linear search where the match condition requires some
complicated evaluation, for example:
bool found = false;
int current = 0;
while ( ! found && current != end ) {
// maybe set found...
}
The tutorial you mention:
NOT: The NOT operator accepts one input. If that input is TRUE, it returns FALSE, and if that input is FALSE, it returns TRUE.
it means NOT operator is unary operator means single operand(not a binary operator)
like && and||` are binary operators and there syntax is:
result = operand1 && operand2
result = operand1 || operand2
Unary is:
result = !operand1
and its result values is revert of operand value id operand1 = True then result would be False and if operand1 = False result is True.
same is written there:
For example, NOT (1) evaluates to 0, and NOT (0) evaluates to 1. NOT (any number but zero) evaluates to 0. In C and C++ NOT is written as !. NOT is evaluated prior to both AND and OR.
in c/c++ 0 is False and
Non 0 is equivalent to True.
there is couple of good examples too!
(1).
!( 1 || 0 )
We know 1 || 0 is 1 means true and application of NOT operator makes it 0 means False:
!( 1 || 0 )
=> ! (1)
=> 0 that is false
Do you notice in this expression we have two operators logical || or and ! NOT operator.
!( 1 || 0 )
^ ^
NOT OR
and notice for OR operator || there is two operands bit single for unary NOT
! operator is used for negation purpose in bool condition checks. There are many places you can use it. Simple example:
if (!existInArray(A, i))
check if i is NOT exist in array.
The point of the ! operator is to make an expression that is false into a true expression. It is most often used as a replacement for == false or == 0. It often makes the expression easier to read:
if (p == NULL || p->next != NULL)
is the same as :
if (!p || p->next)
[Ok, so "easier to read" here is obviously quite subjective].
You have quite a number of answers explaining the NOT operator.
I am not a big fan of the ! operator myself. It is not nearly as visible as it should be (in that, it reverses the meaning of the clause).
For example, despite several years of programming in C++, it still takes me several seconds to parse if ( ! ptr ) as opposed to if ( ptr == NULL ) which instantly conveys me its meaning.
Does if ( ! (i % 2) ) check for even or odd numbers? If you didn't have the answer after your eyes went past the '?', and/or had to review the if condition again, you have just made my case.
Reviewing posts, I agree with some of the posters that the NOT operator has valid uses when applied to bools and function calls. Using ! while processing streams is considered idiomatic.
That said, nearly every programmer I know has been bitten by strcmp. I worked in a shop that has a few #defines such as #define STRCMP_EQUAL 0 etc., and required the check to be written as if ( STRCMP_EQUAL == strcmp(str1, str2) ) which, in my opinion, is orders of magnitude more explicit than if ( ! strcmp(str1, str2) ).
! operator could be used with user defined datatypes(classes and structs in c++).
like every operator(expect . : and ::) !operator could be overloaded. See the following scenario.
//A is empty if memeber size is 0, and no further operations are allowed on other members if
// class is empty.
class A{
int size;
int lot;
int price;
public:
bool operator!()
{
if(lot)
return true;
else
return false;
}
};
A AObj;
//Aobj has size greater than 0
if(!Aobj)
{
//code to Fill or reuse the object.
}
The point of the ! operator is to make an expression that is false into a true expression. It is most often used as a replacement for == false or == 0. It often makes the expression easier to read:
if (p == NULL || p->next != NULL)
is the same as :
if (!p || p->next)
[Ok, so "easier to read" here is obviously quite subjective].

Will a modern compiler automatically optimize the following C++ code?

If i use hte following codes , will the compiler optimize it like a switch structure , which uses a binary tree to search for values ?
if ( X == "aaaa" || X == "bbbb" || X == "cccc" || X == "dddd" )
{
}
else if ( X == "abcd" || X == "cdef" || X == "qqqq" )
{
}
It's just an example , there's no pattern of what's inside the quote symbol
UPDATE
Ok , X is a string , but i don't really think it matters here , i just want to know , when everything inside the if was all about single variable , will it be optimized.
The values WILL be compared one after the other as it is a requirement of the || or, the short-circuit operator. So, here two things will happen:
X will be compared one-by-one from right-to-left.
There will be NO MORE comparisons after any comparison that succeeds (Since it is the short-circuit OR operator) i.e. in the following case
For example:
int hello() {
std::cout<<"Hello";
return 10;
}
int world() {
std::cout<<"World";
return 11;
}
int hello2() {
std::cout<<"Hello2";
return 9;
}
int a = 10;
bool dec = (a == hello() || a == world())
bool dec = (a == hello2() || a == hello() || a == world())
The output for the first statement will be:
Hello
as a == world() will not be executed, and for the second Hello2 Hello, as the comparisons keep on happening till the first success.
In case of the && operator, the comparisons keep on happening until the first failure (as that is enough to determine the outcome of the entire statement).
Almost certainly not. Binary search requires some sort of ordering
relationship, and an ability to compare for less-than. The compiler
cannot assume such exists, and even if it does find one, it cannot
assume that it defines an equivalence relation which corresponds to
==. It's also possible that the compiler can't determine that the
function defining the ordering relationship has no side effects. (If it
has side effects, or if any operation in the expression has side
effects, the compiler must respect the short circuiting behavior of
||.) Finally, even if the compiler did all this... what happens if I
carefully chose the order of the comparisons so that the most frequent
case is the first. Such an “optimization” could even end up
being a pessimization.
The “correct” to handle this is to create a map, mapping the
strings to pointers to functions (or to polymorphic functional objects,
if some state is involved).
It probably depends on the flags you set. Binary trees are faster for search but usually require more code to be handled. So if you optimized for size it probably wont. I'm not sure if it will do it anyway. You know, gcc is optimized according to a LOT of flags. O1, O2, O3, O4 are just simple forms to indicate big groups of flags. You can find a list of all the optimization flags here: http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
Try to search for strings, binary trees, etc in that page.
Best way to test this is the example like below.
int a = 0;
int b = 0;
if(a == a || b++) {
...
}
cout << b;
value of the b variable should be 0 at the end. b++ part won't be executed. that's the expected behaviour but there might be some exceptions depending on the compiler and its optimization settings. even many scripting langauges like JavaScript behaves this way.

Is it good practice to use the comma operator?

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.

Why does this if executes while I have not given any input?

Here is my code snippet:
int a;
if(a=8)
cout<<"Its right";
else
cout<<"Not at all";
getch();
return(0);
I'm getting the output Its right while I've not give any input there its just a assignment to the a=8.
**Borland Compiler** gives the following 2 warnings and executes the code.
1: Possible incorrect assignment (a=8)
2: 'a' is assigned a value that is never used.
When you write:
if(a=8)
You're assigning 8 to the variable a, and returning a, so you're effectively writing:
a = 8;
if(a)
This is non-zero, and hence treated as "true".
I (and the compiler) suspect you intended to write (note == instead of =):
if(a==8)
This is why you get the warnings. (Note that, in this case, a is still uninitialized, so the behavior is undefined. You will still get a warning, and may still return true...)
a = 8 assign 8 to a and returns the value of the assignment, that is 8. 8 is different from 0 and thus is considered true. the test apsses, and the program outputs "Its right".
you may have written if ( a == 8 ) which correctly tests the value of a without changing its value.
if(a=8)
implies assign a value of 8 to a and then use it to evaluate for the if statement. Since 8 is nonzero it essentially translates to TRUE (any value that is non-zero is true).
The first warning is because it's a frequent typo to write = in a condition test where you meant ==. The philosophy behind the warning is that it's a lesser burden for a programmer to rewrite if(a=b) to, say if((a=b)!=0) in the few cases he wants that, than to spend frustrating hours debugging the results if he mistakenly got an assignment instead of a comparison.
The second warning is just what it says: It looks like a mistake to have a local variable that you assign a value to but never use.
Since they are just warnings, you're free to ignore them if you think you know what you're doing. The compiler may even provide a way for you to turn them off.
Everyone else's answer is correct :)
if (a = 8) // Sets a to be 8 (and returns true so the if statement passes)
if (a == 8) // Check to see if a is equal to 8
I just want to add that I always (force of habit!) write if statements this way :
if (8 == a) {
Now, if I miss out one of the =, the compiler doesn't give me a warning, it gives me an error :)
You need a == (double equals). Single = is an assignment; when treated as an expression as you have done here, it evaluates to the value assigned, in this case 8. 0 is treated as False and anything else is True, so (a=8) == 8 == True.