Different between '(!server[i].type==-1)' and '(server[i].type!=-1)'
Server is a struct array have type and amount two members.
server[0] type:-1 amount: 100
server[1] type: 0 amount: 50
server[2] type: 1 amount: 50
I want to calculate the sum of amounts of type not -1.
I think these two codes are same
for(int i=0;i<3;i++) {
if(!server[i].type==-1)
total+=server[i].amount;
}
for(int i=0;i<3;i++) {
if(server[i].type!=-1)
total+=server[i].ptime;
}
But i found the first one not work.Can someone tell me why this happen?Thank you very much.
Well server[i].type != -1 is true if server[i].type is not equal to -1.
On the other hand, !server[i].type==-1 due to operator precedence evaluates as (!server[i].type) == -1, which is never going to be true because the left hand side is either going to be 0 or 1, unless server[i].type has operator! overloaded... which I'm assuming is not the case. The equivalent version would be !(server[i].type == -1).
The unary operator ! is the boolean inversion operator, i.e.
!true → false
!false → true
The binary operator != is the "not equal" operator, i.e. the boolean inverse of "equal to"
a != b → true <=> a == b → false
or written slightly differently
(a != b) == !(a == b)
Take note of putting the boolean inverse operator in front of a pair of parentheses. The reason for that is, that the boolean inversion operator has a higher precedence than the boolean equality operator. Which means that !a == b is equivalent to (!a) == b.
In C and by extension C++ every nonzero value is considered boolean true, and zero is boolean false. Also the result of boolean operators is specified to be either 0 (→false) or 1 (→true).
Now let's look at your two different expressions "!a==-1 and a!=-1"
Since ! is a boolean operator the result of !a is defined to be either 0, or 1. So in case a is nonzero, i.e. true (!a) → 0 thus 0==-1 → false as for a being zero (!0) → 1 thereby 1==-1 → false. Hence the expression !a==-1 will always yield false.
a!=-1 on the other hand is comparing the value of a with -1. Its boolean algebra equivalent would be !(a==-1).
Related
This question already has answers here:
"IF" argument evaluation order?
(6 answers)
Closed 1 year ago.
So I have this program that returns "result: true"
if (true == false != true) {
cout << "result: true";
}
else {
cout << "result: false";
}
even if we flip the comparison operators inside of the if-statement, the compiler still evaluates the expression to be true
if (true != false == true)
My question is:
How does the compiler actually evaluates the expression?
and to which comparison operator out of the two present inside of the if-statement, preference is given?
The answer to both of your questions is operator precedence. The == and != operators get the same precedence, meaning they will be evaluated in the order given.
So in true == false != true, is evaluated as (true == false) != true first statement true==false being false, the full statement now becomes false!=true which evaluates to true
Similarly, 2nd statement true != false == true becomes (true != false) == true which evaluates to true at the end
EDIT:
After reading #Pete's comment, I did some more reading. Apparently there is an associativity property related to these kinds of situations
From https://en.cppreference.com/w/cpp/language/operator_precedence
Operators that have the same precedence are bound to their arguments in the direction of their associativity. For example, the expression a = b = c is parsed as a = (b = c), and not as (a = b) = c because of right-to-left associativity of assignment, but a + b - c is parsed (a + b) - c and not a + (b - c) because of left-to-right associativity of addition and subtraction.
For this particular case, the compiler evaluates the expression from left to right, as "==" and "!=" are of equal precedence.
As mentioned above, these two operators have the same precedence.
For more information check out C++ Operator Precedence
Here is a part of code
int main()
{
int x=5,y=10;
if(x=!y)
{
cout<<"h";
}
else
{
cout<<"p";
}
getch();
}
The output was p, please explain, how the code works and the meaning of x=!y.
Looks like a typo that produces valid code. Expanding it helps--
if (x = (!y))
Since y is 10, !y == 0, and assignments themselves produce a value. In particular the value of x = 0 is 0, so the test evaluates to 0 and that's why you get the result.
But this is a crazy thing to write in this context, presumably what was, or what should have been intended was
if (x != y)
I.e., not-equals.
x=!y is an assignment.
x is being assigned the value of !y expression, which is a logical "NOT" operation. This operation returns true if the operand is zero, or false otherwise. The value true becomes 1 when assigned back to int; false becomes zero.
In C and C++ it is OK to use assignment expressions inside if conditionals and other control statements, such as for and while loops. The value being assigned is used to evaluate the condition, and the assignment itself is performed as a side effect. In this case, the condition is !y.
This question already has an answer here:
The Definitive C++ Book Guide and List
(1 answer)
Closed 7 years ago.
I'm less than a year into C++ development (focused on other languages prior to this) and I'm looking at a guy's code who's been doing this for two decades. I've never seen this syntax before and hopefully someone can be of some help.
bool b; // There exists a Boolean variable.
int i; // There exists an integer variable.
sscanf(value, "%d", &i); // The int is assigned from a scan.
b = (i != 0); // I have never seen this syntax before.
I get that the boolean is being assigned from the int that was just scanned, but I don't get the (* != 0) aspects of what's going on. Could someone explain why this person who knows the language much better than I is doing syntax like this?
Have a read here:
http://en.cppreference.com/w/cpp/language/operator_comparison
The result of operator != is a bool. So the person is saying "compare the value in i with 0". If 'i' is not equal to 0, then the '!=' returns true.
So in effect the value in b is "true if 'i' is anything but zero"
EDIT: In response to the OP's comment on this, yes you could have a similar situation if you used any other operator which returns bool. Of course when used with an int type, the != means negative numbers evaluate to true. If > 0 were used then both 0 and negative numbers would evaluate to false.
The expression (i != 0) evaluates to a boolean value, true if the expression is true (i.e. if i is non-zero) and false otherwise.
This value is then assigned to b.
You'd get the same result from b = i;, if you prefer brevity to explicitness, due to the standard boolean conversion from numeric types which gives false for zero and true for non-zero.
Or b = (i != 0) ? true : false; if you like extraneous verbosity.
(i != 0) is an expression that evaluates to true or false. Hence, b gets the value of true/false depending on the value of i.
This is fairly fundamental syntax. The != operator performs a "not equal to" comparison.
You may be being confused by the shorthand of initialising a bool directly from the result of a comparison operator, but the syntax itself is not esoteric.
The program is essentially equivalent to:
bool b;
int i;
sscanf(value, "%d", &i);
if (i != 0)
b = true;
else
b = false;
The key is that i != 0 is itself an expression that evaluates to true or false, not some magic that may only be used in an if statement.
Basically, if the condition (i not_equal_to 0 ) is satisfied, b gets the value "true". Else b gets the value "false".
Here, "i != 0" is a boolean expression that will be true if "i" is non-zero and false if it is zero.
All that is happening here is the result of that expression is being assigned to a variable.
You could also do things like...
boolean canDrinkAlcohol = (person.age() >= 18 && person.country.equals("UK") || person.age() >= 21 && person.county.equals("US"));
...
if(canDrinkAlcohol) {
...
}
or something
This question already has answers here:
Is short-circuiting logical operators mandated? And evaluation order?
(7 answers)
Closed 8 years ago.
I'm getting it difficult to understand how the following programs work, kindly help me in understanding.
int x=2,y=0;
(i)
if(x++ && y++)
cout<<x<<y;
Output:
(ii)
if(y++ || x++)
cout<<x<<" "<<y;
Output: 3 1
(iii)
if(x++||y++)
cout<<x<<" "<<y;
Output: 3 0
Kindly explain me how the program is working and also, what makes the difference between (ii) and (iii).
You are looking at a "C++ puzzle" which is using two languages tricks.
The first is that postincrement uses the value of the variable first, then increments the variable.
So x++ has the value 2 in the expression and then x becomes 3
y++ has the value 0 in the expression, and then y becomes 1
&& is and
|| is or
both operators are short-circuiting.
Look at && first.
In order for and to be true, both sides must be true (non-zero)
Since it is x++ && y++, first the x++ happens, and since it is non-zero (true)
the y++ has to happen to determine whether the result is true or not.
Therefore x is 3 and y is 1.
The second case is the same. y is zero, but in order to determine if the OR is true,
the if statement executes the second half of the expression.
The third case, since it is in the opposite order, never executes y++ because
x++ || y++
the first half being x++, it is already true, so the compiler does not bother to execute the second half of the test.
int x=2,y=0;
Condition in if() is evaluated according to the rules:
operator && evaluates left operand first and if the value is logically false then it avoids evaluating the right operand. Typical use is for example if (x > 0 && k/x < limit) ... that avoids division by zero problems.
operator || evaluates left operand first and if the value is logically true then it avoids evaluating the right operand. For example if (overwrite_files || confirm("File existing, overwrite?")) ... will not ask confirmation when the flag overwrite_files is set.
To understand the following it is also important to note that x++ is postincrementation what means that in if( x++) x has the old value but just in the next line (or even same line but after if() was tested) x is incremented.
(i)
if(x++ && y++) // x=2,y=0;
// 2 so y++ is evaluated
cout<<x<<y; // skipped, but now x=3,y=1;
Output:
(ii)
if(y++ || x++) // x=2,y=0;
//0 so x++ is evaluated
cout<<x<<" "<<y; // x=3,y=1;
Output: 3 1
(iii)
if(x++||y++) // x=2,y=0;
//2 so y++ is not evaluated
cout<<x<<" "<<y; // x= 3,y=0;
"IF" argument evaluation order?
In C++ (and a few other languages) && and || are your logical operators in conditions. && is the logical AND operator and || is the logical OR operator.
When using these in a condition, the result of the condition is dependent on what is on either side of these operators and is read as if you were just saying the words.
Example:
if(thisNum > 0 && thisNum < 10) is read as "if thisNum is greater-than zero AND less-than 10, the condition will be true." Therefore, any number between 0 and 10 will make the condition true.
if(thisNum > 0 || thisNum < 10) is read as "if thisNum is greater-than zero OR less-than 10, the condition will be true." Therefore, ANY number at all will make this statement true because only one part of this statement has to be true to evaluate to TRUE.
A more detailed explanation on how these work is this:
OR (||) - If EITHER or BOTH sides of the operator is true, the result will be true.
AND (&&) - If BOTH and ONLY BOTH sides of the operator are true, the result will be true. Otherwise, it will be false.
There are many more explanations, including truth tables around the internet if you do a Google search to assist in understanding these.
As for your examples.
if(x++ && y++)
cout<<x<<y;
You are doing an if statement that is comparing the the values of x and y. The important thing to remember is that you are NOT comparing the values together. In C++, and non-zero value will evaluate to TRUE while a zero value will result in FALSE. So, here you are checking to see if x AND y are TRUE and then increasing their values by one AFTER the comparison. Since x = 2 and y = 0, we have one TRUE value and one FALSE value and since we have a && (AND) operator between them we know the result of the condition is FALSE (since both aren't TRUE) and the output is skipped.
if(y++ || x++)
cout<<x<<" "<<y;
In this example, we are doing the same thing EXCEPT we are doing a logical OR operation instead of AND (since we have || and not &&). This means, as I said above, that only one part of the condition has to be TRUE to result in TRUE. Since our values are still x = 2 and y = 0, we have one TRUE value and one FALSE value. Since part is TRUE, the whole condition is TRUE and the output occurs.
The reason the result is 3 1 and not 2 0 is because of the ++ operators after the variables. When the ++ operators are after the variable, it will add one AFTER the rest of the line has occurred and done the actions it needs. So it does evaluates the condition THEN increases the values by one.
if(x++||y++)
cout<<x<<" "<<y;
This example is EXACTLY the same, the only difference is that the values have been swapped. And since it is an OR (||) operation, only one part has to be TRUE. And as before, we have one TRUE value (since x is non-zero) and one FALSE value (since y is zero). Therefore, we have a TRUE result, meaning the output is NOT skipped and we get the answer 3 1 again (since the ++ operators came AFTER the variables).
Now, speaking of the ++ operator. What if in the first example it had been:
if(++x && ++y)
cout<<x<<y;
We would get a DIFFERENT result in this situation. Since the ++ operator comes BEFORE the variables, the first thing that happens is that the values are increased by one AND THEN the condition is evaluated. Since our new values would be x = 3 (TRUE) and y = 1 (also TRUE), we can conclude that we would get the same result as the other two examples since BOTH values are TRUE (which, since we have an AND (&&) operator, BOTH variables have to be TRUE to result in TRUE).
Hope this helps.
EDIT:
One of the other answers made an excellent point about the second and third examples. Result wise, there is no difference. HOWEVER, in terms of how it is evaluated there is a difference.
C++ automatically does something called "short-circuit evaluation". This means, it will skip any evaluations if it knows the result is already going to be TRUE or FALSE. This means that with an OR operation, if the first part is TRUE it will just skip the second part since it already knows the result HAS TO BE TRUE. (Remember, with OR only one part of the comparison has to be TRUE.) So this means that IF the first part is FALSE then the program HAS TO evaluate the second part too, since it determines whether the result will be TRUE or FALSE.
With an AND operation, it will do the opposite. If the first part is FALSE then the program knows the result has to be FALSE and will skip the rest. However, if the first part is TRUE then the program HAS TO evaluate the rest to determine if the result is TRUE or FALSE.
In terms of your examples, this means the second one HAS TO evaluation both sides since the first part results in FALSE.
In the third example, the second part is skipped because the first part is TRUE, meaning the whole condition is TRUE.
For or(||) operator, if the expression of left side is true, it will ignore the expression of right side.
For and(&&) operator, if the expression of left side is false, it will ignore the expression of right side.
This is the answer of your question what makes the difference between (ii) and (iii).
In the output (ii), it is:
as the time where compiler is evaluating y, y is equal to 0 so the statement is false it s evaluating the other member x which is equal to 2 so the statement is true. And then it operates the increment operator.
In the output (iii), it is:
as the time where compiler is evaluating x, x is equal to 2 so the statement is true as the operator of the condition is || it won't evaluate the other expression so the y++ is ignored. Only x will be incremented.
I didn't think these if's would compile but they do:
if (a>>b&&c&&d)
if (month==1,2,3,5,7,9,10)
The first I'm clueless about. In the second statement is the comma supposed to be an (||) or operator ?
Syntax wise was it always this way or was it introduced some time ago ?
I'm using Visual Studio 2010.
if (a>>b && c && d)
it is equal to
if ((a>>b) && c && d)
if the result of a shifted right b times evaluates to a bool, c and d also evaluates to bool respectively, then all these booleans will be AND-ed to each other.
In your context, the all expressions within commas will be evaluated and then the last expression will be passed to if expression:
if (month==1,2,3,5,7,9,10) -> is equal to
if (2,3,5,7,9,10) -> is equal to
if (3,5,7,9,10) -> is equal to
if (5,7,9,10) -> is equal to
if (7,9,10) -> is equal to
if (9,10) -> is equal to
if (10)
which is always true.
It's not suppose to be || or &&. If you want OR or AND write it like below:
if (month==1 || month==2 || month==3 || ....)
or
if (month==1 && month==2 && month==3 && ....)
// Also month can not simultaneously be equal to more than one value!
// then, it's equal to
if (false)
The first if statement would be evaluated like:
if(((a >> b) && c) && d)
Essentially bitshift a by b bits and then logical and with c and then with d
The second is the comma operator which will evaluate the first term and throw it away, then the second, and so on and return the result of the final term. So in our case the statement is equivalent to:
if(10)
which is always true.