4

I can't get it to work in CodeBlocks What will this code print? :

printf( "%hu" ,  ‐1 );
Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
  • 2
    When you say that you "can't get it to work", what do you mean by that? – Some programmer dude May 17 '15 at 17:20
  • 4
    It's Undefined ... a possible outcome is that your program paints the ceiling yellow. – pmg May 17 '15 at 17:20
  • You can [read this](http://stackoverflow.com/questions/19842215/wrap-around-explanation-for-signed-and-unsigned-variables-in-c). – Iharob Al Asimi May 17 '15 at 17:20
  • Use online compilers...like ideone – Subinoy May 17 '15 at 17:24
  • 1
    @pmg it's not undefined, because the argument will be converted to `unsigned short` and that conversion is defined. – Iharob Al Asimi May 17 '15 at 17:27
  • 2
    @iharob: thereis no conversion. `-1` has type `int`; `printf` is a function accepting a variable number of arguments. All values that fit the range of `int` get passed to `printf()` as `int`s. It worlks like this whether you included `` (not including the header is another error) – pmg May 17 '15 at 17:33
  • @pmg I assume that inside `printf()` the argument gets converted according to the format specifier, which in some situations would cause undefined behavior. I haven't ever examined `printf()` implementation in detail to tell if I am right or not, so I just suppose it will be extracted from the variable arguments like `va_arg(args, unsigned int)`. – Iharob Al Asimi May 17 '15 at 18:08
  • @iharob `fprintf()` received an `int` (`-1`) yet was expecting an `unsigned` (`"%hu"`). Thus "If a conversion specification is invalid, the behavior is undefined". Many machines will take that `int -1` bit pattern and assume is is a bit pattern for `unsigned`, cast that pattern to `unsigned short` and merrily produce 65535, but it is still UB. – chux - Reinstate Monica May 18 '15 at 03:49
  • @Александар Стјепановић Use `printf( "%hu" , (unsigned) ‐1 );` – chux - Reinstate Monica May 18 '15 at 03:50

1 Answers1

7

It will print 65535

"%hu" is an unsigned short int which is 16 bit.

-1 is "all-ones", e.g. 0xffff.ffff, but since it gets converted to short it is only 0xffff. Which is 65535 as unsigned.

idbrii
  • 10,975
  • 5
  • 66
  • 107
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • Note: `unsigned short int` which is 16 bit is often true, but not defined by C. C defines `unsigned short int` to be at _least_ 16 bit. `-1 is "all-ones"` is also very often true (2's complement) but not defined by C to be so. – chux - Reinstate Monica May 18 '15 at 03:54
  • @chux - True. In principle we can't tell what the code would print without knowledge of the system being used. However, I'm confident that most systems out there uses 16 bits for shorts and 2's complement representation for signed integers. – Support Ukraine May 18 '15 at 06:23