taurus05
taurus05

Reputation: 2546

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.

Upvotes: 2

Views: 61

Answers (2)

dbush
dbush

Reputation: 223739

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);

Upvotes: 3

Dan Bonachea
Dan Bonachea

Reputation: 2477

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.

Upvotes: 0

Related Questions