Search code examples
functionsyntaxreturn

Why the final result varies?


When returning from a function, The following coding style does NOT seem to work -

    return (int) minim(mid-l,r-mid) + (int) (mid+mid==n)?1:0;

But the following code is working fine -

    int x = minim(mid-l,r-mid);
    int y = (mid+mid==n)?1:0;
    return x+y ; 

mid, l, r, n are all integers.

Can someone please help me understand why?


Solution

  • You need to add parentheses as '+' takes precedence over the ternary operator '?:'

    return (int) minim(mid-l,r-mid) + ((int) (mid+mid==n)?1:0);