What does the line x=!y mean - c++

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.

Related

What does it mean to evaluate in c++?

I cannot understand what it means to evaluate something in c++. I have this sentence: " Its syntax is:
condition ? result1 : result2
If condition is true, the entire expression evaluates to result1, and otherwise to result2." I know what the point is but I can't really get the meaning of the word "evaluate" straight in this context. Does it mean something like to continue, to check or what?
Thanks! Much appreciated
Every expression has a value. That value is obtained by evaluating the expression. And in some forced contortion of the English language, we sometimes say that "the expression evaluates to [something]".
The evaluation of expressions generally happens at runtime, it is a runtime property of your program. (The exception are constant expressions.)
The rules for evaluation are defined recursive:
A literal evaluates to the value it represents, e.g. 5 evaluates to the value "5".
An expression a + b evaluates to the mathematical sum of the values of the expressions a and b. (So to evaluate the expression a + b, you first have to evaluate the expressions a and b.)
The expression a = b evaluates to the new value of a (and has a side effect, which is to change the value of the lvalue designated by a to the value of b).
... and so on ...
The expression c ? a : b evaluates to the conversion of either a or b, depending on the value of c, to the common type of the types of a and b.
Note that not all expressions are evaluated. For example, in the expression sizeof(+a), neither the subexpression +a nor the subexpression a are evaluated. Similarly, in the conditional expression the unused expression is not evaluated, and in logical expressions, the short-circuited dead expression is not evaluated.
"Undefined behaviour at runtime" is usually a consequence of expression evaluation.
The conditional operator evaluates an expression, returning one value if that expression evaluates to true, and a different one if the expression evaluates as false. Its syntax is:
condition ? result1 : result2
If condition is true, the entire expression evaluates to result1, and otherwise to result2.
7==5 ? 4 : 3 // evaluates to 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3 // evaluates to 4, since 7 is equal to 5+2.
5>3 ? a : b // evaluates to the value of a, since 5 is greater than 3.
a>b ? a : b // evaluates to whichever is greater, a or b.
I can't really get the meaning of the word "evaluate" straight in
this context
it means that the expression has a single value after evaluation . for example in this
7==5 ? 4 : 3 // evaluates to 3, since 7 is not equal to 5.
the expression evaluates to 3 (i.e the value of expression is 3)
before evaluation it could have been 4 or 3 but after evaluation the expression equals to 3
It is shorthand syntax of if else. If the condition of the expression (condition) is true result1 will be executed else result2.
It is the short form of if else, Like.
if(condition){
result1;
}else{
result2;
}
Practical example.
int age = 25;
age >= 25 ? cout << "Result 1" : cout << "result 2";
Explanation: If age is greater than or equal to 25, Result 1 else Result 2.
Evaluate means that if you get true from the condition(expression) result1 and if you get false result2.
Firstly, we'll take a complete statement, as the one you have posted is incomplete:
store = condition ? result1 : result2
If condition is true, the entire expression evaluates to result1, and otherwise to result2
This means that if the expression, which is called condition in your shortened if-statement, is true, then result1 is stored in the variable on the left-hand side of the equation, which is store here.
On the other hand, if conditionis not true, then result2 will be stored in store. That's all what the expression means.
This kind of expression is a shortened if-else statement. If you were to convert this statement into a full if-else statement, then it would look something like:
if (condition == true)
store = result1;
else
store = result2;
Here is an example of this kind of statement:
Suppose we have:
int num = 5;
int var = (num == 5) ? 6 : 10;
Then we can expand this statement to be rewritten with the same meaning as follows:
int num = 5;
int var;
if (num == 5)
var = 6;
else
var = 10;
In both cases here, the resulting expression results in 6 being stored in var.
So in short, evaluates simply means that the resulting expression based on the if-else comparison is evaluated, and the resulting value is passed to the variable on the left. Sometimes, there may not be a variable on the left side, and in that case, the function or expression being "evaluated" will be run. An example like:
(num == 5) ? cout << "result1" : cout << "result2";
Will output result1 in the end.
Also, an example like:
(num == 5) ? cout << 5 + 23 : cout << 4 + 32;
Will evaluate the first expression (since numis initialized to 5 from the previous example) to 28, and then output that.
Hope this helps.

Integer to Boolean strange syntax [duplicate]

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

Operator Precedence

I have a sample midterm question that I am not too sure about. Here it is:
#include <iostream.h>
void f( int i )
{
if( i = 4 || i = 5 ) return;
cout << "hello world\n" ;
}
int main()
{
f( 3 );
f( 4 );
f( 5 );
return 0;
}
So I understand that the logical OR operator has a higher precedence and that it is read left to right. I also understand that what's being used is an assignment operator instead of the relational operator. I just dont get how to make sense of it all. The first thing the compiler would check would be 4 || i? How is that evaluated and what happens after that?
Let's add all the implied parentheses (remembering that || has higher precedence than = and that = is right-associative):
i = ((4 || i) = 5)
So, it first evaluates 4 || i, which evaluates to true (actually, it even ignores i, since 4 is true and || short-circuits). It then tries to assign 5 to this, which errors out.
As written, the code doesn't compile, since operator precedence means it's i = ((4 || i) = 5) or something, and you can't assign to a temporary value like (4 || i).
If the operations are supposed to be assignment = rather than comparison == for some reason, and the assignment expressions are supposed to be the operands of ||, then you'd need parentheses
(i = 4) || (i = 5)
As you say, the result of i=4 is 4 (or, more exactly, an lvalue referring to i, which now has the value 4). That's used in a boolean context, so it's converted to bool by comparing it with zero: zero would become false, and any other value becomes true.
Since the first operand of || is true, the second isn't evaluated, and the overall result is true. So i is left with the value 4, then the function returns. The program won't print anything, whatever values you pass to the function.
It would make rather more sense using comparison operations
i == 4 || i == 5
meaning the function would only print something when the argument is neither 4 nor 5; so it would just print once in your example, for f(3).
Note that <iostream.h> hasn't been a standard header for decades. You're being taught an obsolete version of the language, using some extremely dubious code. You should get yourself a good book and stop wasting time on this course.
The compiler shall isuue an error because expression 4 || i is not a lvalue and may not be assigned.
As for the expression itself then the value of it is always equal to true because 4 is not equal to zero.

What is the difference between && and ||? [duplicate]

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.

What is this syntax in while loop condition?

while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
I came across this on codegolf
Please explain the usage of ? and : and why is there no statement following the while loop? As in why is there a ; after the parenthesis.
There is a boolean operation going on inside the parentheses of the while loop:
while (boolean);
Since the ternary operator is a boolean operator, it's perfectly legal.
So what's this doing? Looks like modular arithmetic, printing going on over a range up to 101.
I'll agree that it's cryptic and obscure. It looks more like a code obfuscation runner up. But it appears to be compilable and runnable. Did you try it? What did it do?
The ?: is a ternary operator.
An expression of form <A> ? <B> : <C> evaluates to:
If <A> is true, then it evaluates to <B>
If <A> is false, then it evaluates to <C>
The ; after the while loop indicates an empty instruction. It is equivalent to writing
while (<condition>) {}
The code you posted seems like being obfuscated.
Please explain the usage of ? and :
That's the conditional operator. a ? b : c evaluates a and converts it to a boolean value. Then it evaluates b if its true, or c if its false, and the overall value of the expression is the result of evaluating b or c.
So the first sub-expression:
assigns t-i%10 to i. The result of that expression is the new value of i.
if i is not zero, the result of the expression is i/10
otherwise, print j, and the result of the expression is zero (since printf returns a non-zero count of characters printed, which ! converts to zero).
Then the second sub-expression, after ||, is only evaluated if the result of the first expression was zero. I'll leave you to figure out what that does.
why is there no statement following the while loop?
There's an empty statement, ;, so the loop body does nothing. All the action happens in the side effects of the conditional expression. This is a common technique when the purpose of the code is to baffle the reader; but please don't do this sort of thing when writing code that anyone you care about might need to maintain.
This is the Conditional Operator (also called ternary operator).
It is a one-line syntax to do the same as if (?) condition doA else (:) doB;
In your example:
(i=t-i%10 ? i/10 : !printf("%d\n",j)
Is equivalent to
if (i=t-i%10)
i/10;
else
!printf("%d\n",j);
?: is the short hand notation for if then else
(i=t-i%10 ? i/10 : !printf("%d\n",j)<br>
equals to
if( i= t-i%10 )
then { i/10 }
else { !printf("%d\n",j) }
Your while loop will run when the statement before the || is true OR the statement after the || is true.
notice that your code does not make any sense.
while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
in the most human-readable i can do it for u, it's equivalent to:
while (i < 101)
{
i = (t - i) % 10;
if (i > 0)
{
i = i / 10;
}
else
{
printf("%d\n",j);
}
i = ++j;
if (i < 0)
{
i = i - j;
}
else
{
i = j;
}
}
Greetings.
I am the proud perpetrator of that code. Here goes the full version:
main()
{
int t=getchar()-48,i=100,j=-i;
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
}
It is my submission to a programming challenge or "code golf" where you are asked to create the tinniest program that would accept a digit as a parameter and print all the numbers in the range -100 to 100 that include the given digit. Using strings or regular expressions is forbidden.
Here's the link to the challenge.
The point is that it is doing all the work into a single statement that evaluates to a boolean. In fact, this is the result of merging two different while loops into a single one. It is equivalent to the following code:
main()
{
int i,t=getchar()-'0',j=-100;
do
{
i = j<0? -j : j;
do
{
if (t == i%10)
{
printf("%d\n",j);
break;
}
}
while(i/=10);
}
while (j++<100);
}
Now lets dissect that loop a little.
First, the initialisation.
int t=getchar()-48,i=100,j=-i;
A character will be read from the standard input. You are supposed to type a number between 0 and 9. 48 is the value for the zero character ('0'), so t will end up holding an integer between 0 and 9.
i and j will be 100 and -100. j will be run from -100 to 100 (inclusive) and i will always hold the absolute value of j.
Now the loop:
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
Let's read it as
while ( A || B ) /* do nothing */ ;
with A equals to (i=t-i%10?i/10:!printf("%d\n",j)) and B equals to (i=++j<0?-j:j)<101
The point is that A is evaluated as a boolean. If true, B won't be evaluated at all and the loop will execute again. If false, B will be evaluated and in turn, if B is true we'll repeat again and once B is false, the loop will be exited.
So A is the inner loop and B the outer loop. Let's dissect them
(i=t-i%10?i/10:!printf("%d\n",j))
It's a ternary operator in the form i = CONDITION? X : Y; It means that first CONDITION will be evaluated. If true, i will be set to the value of X; otherwise i will be set to Y.
Here CONDITION (t-i%10) can be read as t - (i%10). This will evaluate to true if i modulo 10 is different than t, and false if i%10 and t are the same value.
If different, it's equivalent to i = i / 10;
If same, the operation will be i = !printf("%d\n",j)
If you think about it hard enough, you'll see that it's just a loop that checks if any of the decimal digits in the integer in i is equal to t.
The loop will keep going until exhausting all digits of i (i/10 will be zero) or the printf statement is run. Printf returns the number of digits printed, which should always be more than zero, so !printf(...) shall always evaluate to false, also terminating the loop.
Now for the B part (outer loop), it will just increment j until it reaches 101, and set i to the absolute value of j in the way.
Hope I made any sense.
Yes, I found this thread by searching for my code in google because I couldn't find the challenge post.