Evaluation of logical condition in ternary operator - c++

I do not know whether parens are required before the ternary operator.
Example:
int a,b,d,e,f; // Some numbers
int l = ( a > b || d < e ) ? a : d;
is surely fine, if a>b or d<e then l = a else l = d.
I am not sure if instead
int l = a > b || d < e ? a : d;
is equally valid, and what about longer statements?
int l = ( a > b || d ) && e > f ? a : d;
I guess that my question is: the ternary operator always treat whatever comes before him as a logical expression and evaluates it, and therefore there is no need for parens before it?

Your first example is correct.
And the second statement is equally valid to the first one.
Your second example reads as follows:
(...) have highest precedence and > and < have higher precedence than && which has higher precedence than || which has higher precedence than ?:.
So
if the result of a > b || d (d is converted to 1 if different than 0) is true
and
if the result of e > f is true
then
l=a
otherwise l=b.

Related

How Precedence of Relational Operator handled in C++

According to precedence rules <, >, <=, >= has precedence over !=, ==
I am so confused that how the following statement will be executed
int a=3, b=3;
cout<< (a != b || a <= b);
I know short circuit evaluation and according to precedence rules I guess that compiler will execute a <= b first as it has precedence over != but it is not doing so.
I did little experiment with above statement by changing a <= b-- and changing order of above conditions and it seems that <= and != have same precedence as compiler execute whichever occurred first. Or I am missing something?
Precedence of operators is only relevant to how expressions are bound, not to how they're executed. Execution order is dependent on the "happens-before" relationship and otherwise subject to arbitrary reordering by the compiler.
Relative precedence of two operators also only matters if they are directly adjacent. In a == b <= c, you get a == (b <= c), not (a == b) <= c. In a == b || c <= d, the adjacent pairs are == and || and || and <=. In both cases the comparison operators bind more strongly, so you get (a == b) || (c <= d), making the relative precedence of == and <= irrelevant. If you have a == b + c <= d instead, you first get a == (b + c) <= d, and now you need to compare == and <= again, getting you a == ((b + c) <= d).
As for order of evaluation, || has a rule that its left side is sequenced before its right side (assuming it's not overloaded), because the right side might not get evaluated at all. So the == is executed first. But precedence plays no part at all in this. If you instead had written the non-short-circuiting a != b | a <= b, both sides would eventually get executed (with caveats, see below), but there are no guarantees which side gets evaluated first; precedence does not play a part here.
Caveat: the compiler can still just optimize your code and realize that a != b || a <= b is tautological, and simply replace the entire thing with true.
Precedence is not order of evaluation.
Precedence is about where to put parentheses. a != b || a <= b is parsed as: (a != b) || (a <= b). It's not parsed as like for example: a != (b || (a <= b)) or any other combination of ( ).
After we know where parentheses are, then we can evaluate the expression. The order of evaluation is: (a != b) first. Then || is evaluated. Then, optionally, a <= b is evaluated.
From: https://en.cppreference.com/w/cpp/language/operator_logical
You are looking for the part in ( )
Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both operands
So a != b will be evaluated first.
In your case 3 != 3 so the second operand will be evaluated.
if( (5<5) || (5!=5) || (5==5) || (5>5) )
The precedence left to right, so 5<5, goes to next 5!=5 goes to next 5==5 operand if returns true and 5>5 is not evaluated.
As per Microsoft doc,
The operator <= >= < > has higher precedence than the operator != ==. But as you have applied the logical or || operator the expression will be executed from left to right.
It will handle it as ( ( a != b ) || ( a <= b ) ) meaning, first ( a != b ) will be check, after that, logical ||, and if there's need than this expression ( a <= b ) will be checked ( only if the first expression ( a != b ) is wrong).

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.

I need to know the explanation of this sentence in c++ " b = (c > 5) ? a/c/2 : 0; "

I need to know the explanation of this sentence in C++
I am editing a library for BL0937 where it uses energy monitoring paramteres , I have just used a b c for simplicity
b = (c > 5) ? a/c/2 : 0;
That can be rewritten as
if(c>5)
{
b = (a/c)/2;
}
else
{
b = 0;
}
x ? y : z is a ternary operator that means "if x, then y, otherwise z."
a/c/2 is just a simple chain of division. As the division operator (/) evaluates from left to right, it is equivalent to (a/c)/2.
So your expression first evaluates c>5 and if that is true, it will evaluate to a/c/2, and otherwise 0. The evaluated value (either a/c/2 or 0) will be assigned to the variable b.
I'll mention more rules of operator precedence for c++, in case that you might be confused of the precedence of / and x ? y : z.
Here is an official page for operator precedence: https://en.cppreference.com/w/cpp/language/operator_precedence
From this, you know operator / has much priority to x ? y : z and =, and thus it is firstly calculated from left to right, i.e. a/c/2 equals (a/c)/2. And then x ? y : z has the same precedence as =, calculated from right to left. Now it means:
b = ( (c>5) ? ((a/c)/2) : 0 );
Hope it helps.

Odd if statements

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.

Variable x equals a or b

Is this:
if(x == a || b){//do something}
same as:
if(x == a || x == b){//do something}
?
I think it is not, because in the first case we evaluate if x equals a and if b is true or false.
In the second case, we evaluate if x equals a and if x equals b. And I understand that in the lazy evaluation if x equals a than we are not evaluating further.
But somebody thinks that in the first case we ask if x equals a or b, so I wanna make sure.
No.
In C++, this:
x == a || b // Same as (x == a) || b
Is equivalent to this:
(x == a) || (bool)b
Which evaluates to true if x and a are equal OR if b evaluates to true when converted to bool. In C, on the other hand, it is equivalent to this:
(x == a) || (b != 0)
Which evaluate to true if x and a are equal OR if b is different from 0 (here we must make the implicit assumption that b is of integral type, otherwise this won't compile).
On the other hand, this:
(x == a || x == b) // Same as ((x == a) || (x == b))
Evaluates to true when either x and a are equal OR x and b are equal (i.e., if x is either equal to a or equal to b) both in C++ and in C.
The two expressions are not equivalent. This
if(x == a || b)
is the equivalent of
if( (x == a) || (b))
i.e an OR of x==a and b. In C++, if b evaluates to anything other than 0 or false, it is taken as true.
The second one tests whether x==b instead of simply testing b.
No. In C this is equivalent to:
if(x == a || b != 0)
The first reads as "if x is equal to a, or if b is truthy"
The second reads as "if x is equal to a, or if x is equal to b"
No.
if (x == a || b)
is equal to
if ((x == a) || (bool)b)
because operator == has higher precedence than operator ||. See Operator Precedence Table.
You are almost right, the first case means x equals a OR b is true.
Lazy evaluation means that the expression will be evaluated only until the result is obvious. In an OR expression, for example (x || y), the result will be known when x==true – then the whole expression must be true too. In the case of AND, like (x && y), the result will be evident when x==false. So you are right, if x==a, we know the answer already and no more work is needed.