0

I found this code on fabien sanglard's website. I am new on C Programming Language and I need well explain about this code and How it is possible to be -1 greater that 1.

unsigned int   ui_one       =  1 ;
signed   int   i_one        =  1 ;
signed   short s_minus_one  = -1 ;

if( s_minus_one > ui_one)
    printf("-1 > 1 \n");

if( s_minus_one < i_one) 
    printf("-1 < 1 \n");

#./run
#
# -1 > 1 
# -1 < 1
XBlueCode
  • 785
  • 3
  • 18
John
  • 3
  • 1
  • you are seeing the effects of the "usual arithmetic conversions" (see [C11 6.3.1.8](http://port70.net/~nsz/c/c11/n1570.html#6.3.1.8)), not of some particularty of the types `signed int` and `signed short`. In your case (`(short)-1 < (unsigned)1`) the signed value is converted to an unsigned type (`-1` converts to `0xff...ff`) – pmg Sep 08 '19 at 12:02
  • In hexadecimal, -1 is the value 0xffff, or 65535 if read back as unsigned... – B. Go Sep 08 '19 at 12:05
  • 1
    The title is wrong. The code in the question compares two pieces of code in which the difference is `unsigned int` versus `signed int`, not `signed int` versus `signed short`. – Eric Postpischil Sep 08 '19 at 12:09

1 Answers1

2

Usual arithmetic promotions (6.3.1.8) apply

... Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type. ...

and in if( s_minus_one > ui_one), s_minus_one gets converted to unsigned int.

The conversion is governed by 6.3.1.3p2:

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

so your (unsigned int)s_minus_one will get you UINT_MAX and UINT_MAX is greater than ui_one.

On gcc and clang, you can compile with -Wsign-compare -Wconversion (or with -Wextra) to get warnings about these conversions (https://gcc.godbolt.org/z/dZ6L-y).

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • Thanks @PSkocik. I know this question is not about this post, But what is your suggestion for me to be expert in C programming language and avoid of get confused on problems like this question? I know I should practice and practice and practice, But I need some books to get expert in C and solving this problems. Thanks – John Sep 08 '19 at 14:59
  • @John: That seems like a much bigger question than the original one. :D My quick advice would be: go through the classics (The C Programming Language + Advanced Programming in the Unix Environment), try and build something practical that you actually want, so you stay motivated, and finally, realize what UB is and fear it. The last bit should make you actually go through the C standard. – Petr Skocik Sep 08 '19 at 15:18