Search code examples
c++syntaxbinary-search-treecomparison-operators

Can someone explain the syntax behind this line of code? C++


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


Solution

  • This is the so called "conditional operator" in c++. It works as follows:

    1. the expression before the ? is evaluated and converted to bool,
    2. if it evaluates to true, the second operand is evaluated (i.e. hL in your example),
    3. otherwise, the third operand (hR in your example) is evaluated.
    4. The result is assigned to maxH.

    See here for more detail (go down to the section "Conditional operator").