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.
Related
If I use assignment operators or output functions inside the if condition, why is it taken as a "true" Boolean value?
For example, I do
if(cout << "a"){cout << "c";}
Or
if(int x=7){cout << "c";}
Or even
if(6){cout << "c";}
the outputs are indeed, "c" and "c" and "c" in each case. But we were told that, inside the if condition, we have to use an expression that finally evaluates to a Boolean value, like 1 or 0.
So what is the piece of information I am missing?
In each case the expression is converted to a bool. The value of this bool is true in the three cases that you use (it may not always be true).
if(cout << "a"){cout << "c";}
In this case the expression:
cout << "a"
If find the operator<<(std::ostream&, char const*) definition you will find that the return value is std::ostream&. So this will return a reference to the cout object (of type std::ostream). The stream object has a boolean conversion method explicit bool() which can be used to convert the object to bool. The result of this depends on the state of the object (if it is in a bad (failing) state it will return false).
So here you are checking that the last operation on the stream worked. If it does then print "c". This is commonly used on input streams to validate user intput.
int val;
if (std::cin >> val) {
if (std::cout << "A value was correctly read\n") {
// Add response worked.
}
else
{
// Something bad happened to std::cout
}
}
In the other cases you use int variables. These can be implicitly converted to bool. If the value is non zero then it is true (otherwise false).
Every value inside a condition (or with Boolean conversion) will give you true, unless it equal to 0.
(6) returns => 6 != 0 => true
(x = 7) returns => 7 != 0 => true
(cout << "aa") returns => ostream object.
bool context so calls `ostream::operator bool()`
If the stream is in good state => true
Otherwise => false
In C you can see it with NULL with this declaration:
#define NULL 0
which means that if an pointer equal to NULL it will return you a false in a Boolean conversion.
Examples in C++ for boolean expressions:
int a, b, *c;
char d;
bool e;
a = 0;
b = 2;
c = nullptr;
e = a; // false
e = b - 2; // false
e = c; // false
c = &a;
e = c; // true
e = b; // true
e = a + 1; // true
e = b ^ b; // false
d = 0;
e = d; // false
d = '0';
e = d; // true
In all the cases you've shown, it's still true that you've provided an expression that eventually is convertible to bool. If you look at the << operator of std::cout and similar ostreams, you'll see they all return a reference to the same stream. This stream also defines a conversion to bool operator, which is implicitly called in a context where a bool is expected. This particular conversion returns true if the stream has no errors. Secondly, int x=7 is an initialization, and it returns the value that x was just initialized with; 7 in this case. int in C++ can be implicitly cast to bool to be true if it's not zero, which is why both 7 and 6 evaluate to true in the second and third examples.
I have came across one type of usage of operator =. It was something like this:
A += B == 1;
where A and B are integers and this kind of usage I found in a function body.
I just kind of confused with the second == usage.
Of course I know the meaning of A = B = 1;
Can anybody explain me?
This code:
A += B == 1;
is logically equal to:
bool b = B == 1;
A += b;
Note: bool can be implicitly converted to int (true to 1 and false to 0)
== has higher precedence over +=, so it's executed first
B == 1 is a boolean expression, can be false or true
let's call that bool 'result'.
A += result is an addition + assignment (like A = A + result as you may already know).
Since A is an int in your case, the boolean result is implicitly converted to the number 1 if true, or 0 if false. (it would work similarily for other number types as well)
More on implicit conversions here : http://en.cppreference.com/w/cpp/language/implicit_conversion
So, at the end, this is logically equivalent to "increment A if and only if B is equal to 1" :
if (B == 1)
A += 1;
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.
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.
Is there a c++ operator that i could use for a for loop where it would add or subtract to variables based on whether one of the variables is less than or greater 0.
For instance
int a;
int b;
for(int i=0;i<some_number; i++)
result = a +< b
result = a-> b
No.
You can combine with the ?: operator.
int a;
int b;
for(int i=0;i<some_number; i++)
result = (a < b)? result+b:result-b;
That is if I understood your example correctly.
-> is an existing dereference operator.
Operator ?: is an equivalent to the if...else construct. If the statement before ? evaluates to true, the statement right after the ? gets executed, otherwise the statement after the : gets executed.
Do you want something like this?
result += a > 0 ? b : -b;
Note that this will subtract b if a == 0, which isn't quite what you asked for.
Not directly, but the ternary operator is close.
for(int i=0;i<some_number; i++)
result = (a > 0)?(a):(b);
This line will be equivalent to result = a when a is greater than 0, and result = b elsewise.
It could also be written as result = a?a:b;, but the longer form is more readable.
Not sure if this would be any help?
result = a + (b*(a < b));
result = a - (b*(a > b));
Basically, (a < b) is converted into a boolean, which is basically either 1 (true) or 0 (false). b multiplied by 0 is of course zero, so nothing is added, and b multiplied by 1 is exactly b's value.