the result of assignment Logic operation [duplicate] - c++

This question already has answers here:
In C++ what causes an assignment to evaluate as true or false when used in a control structure?
(6 answers)
Closed 5 years ago.
int a = 5;
if(a = 5)
{
cout<<"111111"<<endl;
}
if(a = 0)
{
cout<<"22222"<<endl;
}
the reslut is
111111
Press any key to continue
acrroding to some commments,assign success,the result is true。
"a = 0" and a = 1" should assign success.but the result is only the first executed....
why ?

Some comments? That seems dodgy and in this case is incorrect.
The result of operator= on ints is the value that has been assigned. In this case a = 5 results in 5 and a = 0 results in 0. Since 5 evaluates as true you see "111111" but since 0 evaluates as false you don't see "22222".
As for why assignment results in the value being assigned, take the case with multiple assignments:
a = b = 5;
This is the same as:
a = (b = 5);
So for this to work as expected (b = 5) must return 5.

The result of a=5 is 5, and the result of a=0 is 0, so your program is like:
int a = 5;
if(5)
{
cout<<"111111"<<endl;
}
if(0)
{
cout<<"22222"<<endl;
}
Since the if statement requires a boolean value, 5 converts to true and 0 converts to false implicitly. so your program is now like:
int a = 5;
if(true)
{
cout<<"111111"<<endl;
}
if(false)
{
cout<<"22222"<<endl;
}
So it will print "111111" only.
"acrroding to some commments,assign success,the result is true"
The result of assignment is the result of expression in the left side.

"a = 0" and a = 1" should assign success.but the result is only the first executed....
Nope. 0 is false, you may as well have written"
if(0) { /* some code which will never execute */ }
The if statement evaluates the result of the expression between the parentheses, which means that the expression itself must be evaluated completely before the condition is checked.

Related

variable value, after ternary operator

I have these lines of code:
int a = 10, b = 1;
a = --b ? b : (b = -99);
cout << "a= " << a << "b= " <<b<< endl;
the output gives me b=-99 as a is not equal to 0(which makes senses) but it also changes the value of a to a=-99 how?
Your code is the equivalent of:
int a = 10, b = 1;
b -= 1; // b == 0
int x;
if (b != 0) x = b;
else x = b = -99;
a = x;
// at this point a and b have the same value
The ternary operator works as follows:
if (--b != 0) { // b is not 0 means true
a = b;
} else { // b is 0 means false
a = (b = -99);
}
You assign the value to a, so --b is 0 which is considered as false. Then you assign to b value -99 and afterward, you assign b to a. So, both variables have their values -99 in the end. Hope it will help you.
According to ternary operator, The first argument is a comparison argument(condition), the second is the result upon a true comparison, and the third is the result upon a false comparison.
So In Your case, the condition is not True, So the false statement get executed.
so now b has -99.
In c, c++, java we've seen, assigns the value of the variable
a = b = -99
In this, the both a & b gets the same value. Like this, ternary operator also assigning the value of the variable from false statement .
(a = (b = -99 ))
I think what is confusing you here is that, in C, an expression (such as b = -99) has both consequences and a value. The consequence of b = -99 is that b is assigned the value of -99; but note also that the value of this expression is -99.
Thus, in a ternary expression, which takes the general form:
lhs = test ? v_if_true : v_if_false;
the expression test is first evaluated and lhs is assigned either v_if_true (if test evaluates to non-zero) or v_if_false (if test evaluates to zero).
In your case, test is --b. The consequence of this expression is that the value of b is decreased by one, and the value of the expression is the resulting (modified) value of b (which will be zero in your code).
So, your ternary expression assigns to a the value of the v_if_false expression which is b = -99 (the brackets you give add clarity to the expression, but don't change its evaluation). So, as mentioned above, this expression (as well as modifying b) also has a calculated value of -99, which is then given to a.
If you wanted to leave a unchanged in the case when the v_if_false expression is executed, then you could do this using the comma operator, as follows (though I would not recommend using such code):
a = --b ? b : ((b = -99), a); // If --b == 0, this becomes a = a
This works because the value of an expression containing the comma operator is the value of the sub-expression after (to the right of) the comma.

what does if(!(x%3)) mean?

I am attempting to solve a hw problem in which I need to write down what the program will output. I am stuck however, on the syntax "if ( !(i%3)). What does that really mean? Does it mean that the program is checking for any i that is divisible by three? aka, is the if statement only runs if i is divisible by three?
int main () {
for (int i=0; i<10; (i<3?i++;i+=2)) {
if (!(i%3)) {
continue;
}
else if (i%7 ==0) {
break;
}
cout << i<< endl;
}
Does it mean that the program is checking for any i that is divisible by three? aka, is the if statement only runs if i is divisible by three?
Correct. The longer version of that check would be
if (i % 3 == 0)
continue;
The most common use case for such branching is probably FizzBuzz.
İt means if i is not(!) divisible by 3 continue.
For example if i is 3,6,9 it won't continue otherwise it will continue.
if (x) where x is int implicitly compared with zero. I.e. if (x) equals to if (x != 0). ! is negation. So if (!x) equals to if (x == 0). And the last step is if (!(i%3)) equals to if ((i%3) == 0) what is the same with check, that i deivisible by 3
The if() statement is false only if the result inside the parentheses is 0 (false). Take a look at your program:
i%3 may return 0 (false), 1 (true), or 2 (true)
The negation operator ! changes the result of the operation (i%3). So, if the i is divisible with 3 the statement will return 0 (false). Being negate, ! it will result in True. Otherwise the result of (i%3) will be true and with the operator ! the result of the hole statement will be false. Basically this code is checking if the value of i is divisible with 3.
Other options will be:
if (0==i%3)
{
/*code*/
}
Your code can be simplified as below
int main() {
for (int i=0; i<10;)
{
if (i % 3 == 0) {
continue;
}
else if (i % 7 == 0) {
break;
}
cout << i << endl;
i = i<3 ? i+1 : i+2;
}
}
When you write a integer variable like i as a condition, what happens is that if i==0 then the result of the condition is false, otherwise it would be true.
Let's check it out in your program, if(!(x%3)), let's name condition= !(x%3), when this condition is true? when x%3 == 0, note that the negation operator ! is behind x%3, so in this case the condition would be equal to true, more formally the condition is equal to :
if(x%3==0)
these kinds of conditions are common, check this example out :
int t = 10;
while(t--){
cout<<t<<endl;
}
The above condition i.e if(!(i%3)) will true when " i is not disvisable by 3"
Hope this helps.
In java and other languages there is a special type to represent booleans and evaluate expressions; in c and its variants there is no such thing, instead an expression is considered "true" if -taken as a integer number- is equal to 0; false for every other value. (Fun fact: this is why you usually end the code by return 0)
So if(x%3) in c is equivalent to if(x%3==0) in other languages. That said, if(x%3) execute the if body when the remainder of x/3 is 0, that is when x is a multiple of 3.
In your code you have the ! before, that -as you may know- "inverts" the expression. That means that if(!(x%3)) can be read as "If the remainder of the integer division of x by 3 is not 0", or alternatively: "If x is not a multiple of 3".
So, basically, you saw it right.
Hope I helped!

Variable changes on it's own in C++

I have a loop going through an array trying to find which index is a string. It should solve for what that value should be.
I can't figure out why, but as soon as the if statements start i becomes 1 which gives my code an error.
I'm not very fluent in C++.
for(int i = 0; i < 4; i++) {
if(auto value = std::get_if<std::string>(&varArr[i])) {
solvedIndex = i;
auto value0 = std::get_if<float>(&varArr[0]);
auto value1 = std::get_if<float>(&varArr[1]);
auto value2 = std::get_if<float>(&varArr[2]);
auto value3 = std::get_if<float>(&varArr[3]);
//i changes to 1 when this if starts??
if(i = 0) {
solvedVar = (*value3 / *value1) * *value2;
} else if (i = 1) {
solvedVar = *value3 / (*value0 / *value2);
} else if (i = 2) {
solvedVar = *value0 / (*value3 / *value1);
} else {
solvedVar = *value1 * (*value0 / *value2);
}
break;
}
}
Note that these variables are declared above. Also, varArr is filled with values:
std::variant<std::string, float> varArr[4];
int solvedIndex;
float solvedVar;
As has been noted, in your if statements, you are using the assignment operator (=) but want the equality comparison operator (==). For your variable i the first if statement sets i equal to 0 and if(0) is the same as if(false). So your program goes to the first else-if which sets i equal to 1 and if(1) evaluates to true. Your code then finishes the block within else if (i = 1) {...} and then ends.
That's because operator= is the assignment operator in C++ (and most languages, actually). That changes the value of the variable to the value on the other side. So, for instance:
x = 0
will change the value of x to 0. Doesn't matter if it's in an if statement. It will always change the value to 0 (or whatever the right hand side value is).
What you are looking for is operator==, which is the comparison (aka relational) operator in C++/ That asks the question "Are these two things equal?" So, for instance:
x == 0
asks is x is equal to 0.

What does the line x=!y mean

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.

How are these evaluated as true?

Consider the following examples:
int x;
if (x = 1)
//...
if (std::cout << "Is it true?")
//...
Both are evaluated as true, but why?
The if (x = 1) is essentially the same as tmp = (x = 1); if (tmp) ...
The "result" of operator << (const char *) is an ostream&, which has an operator bool that the compiler calls to make it "comparable". operator bool will return "false if there was an error, otherwise true". Before C++11, it would return a void*, but the meaning was the same ("false (= 0) if there is an error, true otherwise".
The result of assignment is its left operand, so the value of x = 1 is its left operand x, which has the value of 1 now. And any non-zero integer is treated as true in the condition.
Because x = 1 is an assignment setting x to 1, not a comparison for equality. Comparison is done via x == 1.
It is a common mistake. Often people write 1 == x to catch these errors, since assignment to a constant triggers a compile-time error.
Besides the assignment result for x as mentioned in the other answers the
if (std::cout << "Is it true?")
evaluates to true, because the statement is equivalent to
if ((std::cout << "Is it true?").good())
which checks for the stream state of std::cout.
Both statements return a value other than 0 and are thus considered to be "true".
If you assign a value to a variable, the result of that statement is the assigned value so you can assign multiple variables at once. For example, foo = bar = baz = 1. This works because baz = 1 yields 1, which is then assigned to bar, then to foo. So x = 1 has the value 1 and is thus true.
Next, the std::cout << "foo": the operator<< on a ostream returns the ostream so you can do things like std::cout << "foo" << "bar";. Again, there is a value returned that is not 0 and thus true.
In this condition x = 1 you firstly assign 1 to your x variable, and then test x, so it is exactly the same with:
x = 1;
if( x ) // which is 1, so true
About the output operator <<, the compiler will return true if the output-stream's state cout is ok. So it is not going to be a valid stream if some error occurs.
In the first one, you're assigning the value of 1 to x. A non-zero value will always evaluate to true in a condition.
For the second one, when std::cout << "Is it true?" is called, operator<< will return a reference to std::cout. At that point, the condition is simply reduced to:
if (std::cout)
//
This is now evaluating whether or not std::cout is in a good state.