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!
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!
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--;
}
It is wrong because the operation is not assigning a value to anything...
ternary operations have a return
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--;