0
height[left] < height[right]? left++ : right--;

I want to user the above syntax to replace if/else statement. I think it follows (condition)? doX(): doY() but there's somthing wrong.

Thank you!

Tina
  • 13
  • 2

2 Answers2

3

The ternary operator is an expression, not a statement. You're not assigning the result of the expression to anything, so the compiler doesn't like it.

If you mean this as a statement, use if instead of the ternary operator:

if (height[left] < height[right]) {
    left++;
} else {
    right--;
}
Jesper
  • 202,709
  • 46
  • 318
  • 350
0

It is wrong because the operation is not assigning a value to anything...

ternary operations have a return

Example:

int a=0;
int b=0;
int left=0;
int right=0;
int pos=0;
pos = a < b? left++ : right--;

as you see the variable pos get assigned as result of the ternary operation

in your case you are missing the variable were left++ or right-- is going to be assigned:

??? = height[left] < height[right]? left++ : right--;
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97