What do these operators " > " and " mean? "

Asked

Viewed 187 times

1

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 that part mean (left > right? left : right)?

  • The cond? case_true: case_false is the ternary operator. Returns case_true case the condition in cond be true, return case_false otherwise. The condition is if left > right, number of the left greater than the number of the right. It returns the number of the left if true, and the number of the right if not. I mean, take the big one

3 answers

1


> means greater than, equal in all languages and in mathematics (although it is usually a statement and in programming it is a question that will generate a Boolean result. In this 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 (at the moment the only one like this), ie it has three parts. Its name is conditional operator. Then the value of the second part (after the ? will be the result of every expression if the previous condition is true. If it is false the result will be the last part, that is, what is after the :. This result will be saved in larger.

So he’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 put in the Github for future reference.

0

The equivalence of that would be:

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

The name of this code instruction:

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

is called Ternary Conditional Instruction.

0

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

In simple mode

(condição ? verdadeiro : falso)

before the ? would be the condition and between : the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.