5

Can someone explain to me how

printf("%d", -2<2u?1:-1);

prints out '-1'. I assume there is some kind of implicit conversion going on but I can't seem to grasp it.

Nebeski
  • 610
  • 4
  • 14
  • 7
    Enable all warnings: *"warning C4308: negative integral constant converted to unsigned type"* explains the issue. – Weather Vane Feb 12 '16 at 12:11
  • 1
    Now explain why this code `if( (-2 < 2u ? 1u : -1) > 0) { printf("-1 > 0"); }` prints `-1 > 0` :) – Lundin Feb 12 '16 at 12:31
  • @Lundin You mean something like [This](http://pastebin.com/raw/Ss7pW8hb)? – Michi Feb 12 '16 at 15:36
  • @Michi Obviously you can't compile questionable code with `-Werror` set :) – Lundin Feb 12 '16 at 15:42
  • @Lundin I wasn't sure, what was your Point :) – Michi Feb 12 '16 at 15:45
  • 1
    @Michi The subtle tweak I did was to take a condition operator which always evaluates the result to be the 3rd operand (-1), then make the 2nd operand unsigned (1u). Even though the 2nd operand will never be used, there is an implicit balancing between the 2nd and 3rd operand of the ?: operator, which causes an incorrect result in this case. The conclusion is that the `?:` operator should be used carefully. – Lundin Feb 12 '16 at 15:49
  • @Lundin Nice one :)) – Michi Feb 12 '16 at 16:16

1 Answers1

5

-2 is getting converted to unsigned integer. This will be equal to UINT_MAX - 1, which is definitely greater than 2. Hence, the condition fails and -1 is printed.

CinCout
  • 9,486
  • 12
  • 49
  • 67
  • So that `u` there is converting both -2 and 2 to `unsigned integer`? – Nebeski Feb 12 '16 at 12:14
  • 3
    @Nebeski No, the conversion of -2 to `unsigned int` is an implicit conversion, as mentioned in the title. You can't compare a signed and an unsigned quantity directly, so one is converted to the other. – unwind Feb 12 '16 at 12:18
  • @Nebeski Study "the integer promotions" and "the usual arithmetic conversions". – Lundin Feb 12 '16 at 15:44