My professor is having us change her functions to work for her assignment on Binary Search Trees. I know that this line she has assigns myHeight to whatever value being compared that is greater, but I have no idea how it's actually doing that.
int maxH = (hL > hR) ? hL : hR;
I want to use this in the future since it can save time writing code, but to do that I need to understand the syntax first. Thanks guys
CodePudding user response:
This is the so called "conditional operator" in c . It works as follows:
- the expression before the
?
is evaluated and converted tobool
, - if it evaluates to
true
, the second operand is evaluated (i.e.hL
in your example), - otherwise, the third operand (
hR
in your example) is evaluated. - The result is assigned to
maxH
.
See here for more detail (go down to the section "Conditional operator").
CodePudding user response:
This is known as the conditional operator in C .
"The conditional operator is an operator used in C and C (as well as other languages, such as C#). The ?: operator returns one of two values depending on the result of an expression.
Syntax
(expression 1) ? expression 2 : expression 3 If expression 1 evaluates to true, then expression 2 is evaluated.
If expression 1 evaluates to false, then expression 3 is evaluated instead.
Examples
#define MAX(a, b) (((a) > (b)) ? (a) : (b)) In this example, the expression a > b is evaluated. If it evaluates to true then a is returned. If it evaluates to false, b is returned. Therefore, the line MAX(4, 12); evaluates to 12.
You can use this to pick which value to assign to a variable: int foo = (bar > bash) ? bar : bash; In this example, either 'bar' or 'bash' is assigned to 'foo', depending on which is bigger.
Or even which variable to assign a value to: ((bar > bash) ? bar : bash) = foo; Here, 'foo' is assigned to 'bar' or 'bash', again depending on which is bigger."
https://cplusplus.com/articles/1AUq5Di1/
Using your teacher's example:
int maxH = (hL > hR) ? hL : hR;
This is equivalent to "if hL is greater than hR, then assign the value of hL to maxH, otherwise assign the value of hR to maxH."
CodePudding user response:
The expression condition ? v1 : v2
returns v1
if condition
is true
, v2
otherwise.
CodePudding user response:
int maxH = (hL > hR) ? hL : hR;
is equivalent to
int maxH;
if(hL > hR) maxH = hL;
else maxH = hR;
CodePudding user response:
It's the conditional/ternary operator. It is used as an alternative to short if..else statements. Its syntax is as follows:
condition ? exprIfTrue : exprIfFalse
The condition before the (?) is evaluated as a bool. If it is true, exprIfTrue is executed. If it is false, exprIfFalse is executed. The (:) acts as the separator between the two conditions.
In your case, the condition evaluates if hL is greater than hR and assigns hL to integer max if it is true, or it assigns hR to integer max if it is false.
Note: Besides false, other false expressions could be null, NaN, 0, empty string (""), and undefined.