Search code examples
cconditional-operator

Not getting expected output for ternary operator


Consider the following code in C :

  void main() {
     char *x = "abc";
     char *y = "defgh";
     unsigned int c=0;
     int len = ((strlen(x) - strlen(y)) > c) ? strlen(x) : strlen(y);
     printf("%d\n", len);
  }

I'm getting output as 3, but the condition in ternary operator ((strlen(x) - strlen(y)) > c) is false, because this will be 3-5 > 0 which is false. Hence, the output should be 5. I couldn't understand what went wrong.


Solution

  • The result of strlen is size_t, which is an unsigned type. Thus the expression:

    ((strlen(x) - strlen(y)) > c
    

    effectively expands to:

    (((size_t)3 - (size_t)5) > 0
    

    And ((size_t)3 - (size_t)5) is not a negative number (there are no negative size_t values). It is instead a very large unsigned value (e.g. 0xFFFFFFFFFFFFFFFE for a 64-bit system), which is in fact larger than 0.