2

Suppose I have the following code:

unsigned char c = 0;
printf("%u\n", ~c);

GCC prints the value 4294967295, means it prints the value of ULONG_MAX.

C11 6.3.1.3 Signed and unsigned integers:

  1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
  2. 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.60)
  3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

So, c is promoted to unsigned int before applying operator ~. Thus the result is the one's complement of 0u. Am I right? or is it undefined?

Jayesh
  • 4,755
  • 9
  • 32
  • 62
  • 2
    Shall we assume you meant `x` and not `c`, or vice versa? And fyi, that's a variadic argument list, and [things are a little different](http://en.cppreference.com/w/cpp/language/variadic_arguments). – WhozCraig Nov 04 '17 at 07:19

1 Answers1

4

C does not perform arithmetic in (unsigned) char types. All arguments are promoted first, according to the integer promotions. unsigned char promotes to int, so the result of ~x is -1. You then print this value as an unsigned int, which gives the output you observed.

Florian Weimer
  • 32,022
  • 3
  • 48
  • 92