What do these "and" operators mean? "[Duplicate]

0

The code below is part of an algorithm that shows the height of a binary tree:

int left = height(p->left);
int right= height(p->right);
int larger = (left > right? left : right);
return 1 + larger;

What does this part (left > right? left : right) mean?

    
asked by anonymous 06.12.2017 / 15:45

3 answers

1

> means greater than, equal in all languages and math (although it is usually a statement and in programming it is a question that will generate a Boolean result, in which case you are asking if the value of left is greater than the value of right .

The result will decide what to do with the next operator that is ternary (currently the only one so), ie it has three parts. His name is conditional operator . Then the value of the second part (after ? will be the result of every expression if the previous condition is true. If false the result will be the last part, that is, after : . saved in larger .

So it's like a if , but it's an expression.

This code could be written like this:

int left = height(p->left);
int right= height(p->right);
if (left > right) return 1 + left;
else return 1 + right

I placed GitHub for future reference .

    
06.12.2017 / 15:54
0

The equivalence of this would be:

int larger;
if(left > right){
    larger = left;
}else{
    larger = right;
}

The name of this code statement:

int larger = (left > right? left : right);

is called Ternary Conditional Instruction.

    
08.12.2017 / 05:48
0
int larger = (left > right ? left : right)

In simple mode

(condição ? verdadeiro : falso)

before ? would be the condition and between : the answer

    
08.12.2017 / 09:40