-2

int main(void) 
{ 
    int arr[] = { 2, 3, 4, 10, 40 }; 
    int n = sizeof(arr) / sizeof(arr[0]); 
    int x = 2; 
    int result = binarySearch(arr, 0, n - 1, x); 
    (result == -1) ? printf("Element is not present in array") 
                   : printf("Element is present at index %d", 
                            result); 
    return 0; 
} 

so right beside the (result==-1) is the ? and : . now i've never seen these things before and don't know how they work, are they like True of false statements or like switch-cases?

Mr.Wang
  • 31
  • 1
  • 3
  • This is not a tutorial site. – TomServo Oct 01 '20 at 02:03
  • The ?: is designed for returning a value to an expression. What they did here was make an if statement and then obfuscate it on purpose for no advantage. If it can be done in a more readable way, then it should be. I wouldn't call this the most readable way... – Jerry Jeremiah Oct 01 '20 at 02:07

2 Answers2

0

These are ternary operator, a quick shorthand for if...else:

(condition) ? value_if_true : value_if_false
Wasif
  • 14,755
  • 3
  • 14
  • 34
-1

Its calles ternary operator. If-else equivalent

if(result == -1) 
    printf("Element is not present in array") ;
else
    printf("Element is present at index %d",  result); 

It doesn't mean you can write everything that way. Each statement after ? Mark must have to return a value. Printf function teturns int, the number of characters it printed. Hence this is working. If you pass a void function you will see compilation error.

Popeye
  • 365
  • 3
  • 13