Home > Enterprise >  Not getting expected output for ternary operator
Not getting expected output for ternary operator

Time:01-02

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.

CodePudding user response:

The strlen function has a return type of size_t which is an unsigned integer type. This means that strlen(x) - strlen(y) also has this type. So instead of resulting in a value of -2 you get a result which is a very large positive value. This value is greater than 0, so the condition is true.

If you cast the results of these functions to int, you'll get the expected result.

int len = (((int)strlen(x) - (int)strlen(y)) > c) ? strlen(x) : strlen(y);

CodePudding user response:

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.

  • Related