signness of 0

Is it really needed to specify 0 as an unsigned integer? I mean 0 is always 0 regardless it's signed or not, no? In the below example is the 0U really needed?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>

unsigned invert(unsigned x, int p, int n)
{
    return x ^ (~(~0U << n) << p);
}

int main(void)
{
  unsigned x;
  int p, n;

  for(x = 0; x < 700; x += 49)

    for(n = 1; n < 8; n++)

      for(p = 1; p < 8; p++)

        printf("%u, %d, %d: %u\n", x, n, p, invert(x, n, p));

  return 0;
} 
There is a significant difference between the treatment of signed types vs the treatment of unsigned types. It just so happens that the value we are making unsigned is 0. By default, integer literals are signed.
Last edited on
Being signed and unsigned would affect when you flip the bits with ~.
closed account (10X9216C)
It's to remove ambiguity that might be caused, when is "0" a signed number or unsigned number since it can be either.

1
2
3
4
5
void pup(signed) { std::cout << "s"; }
void pup(unsigned) { std::cout << "u"; }

pup(0); // what do you except to happen here ? Should the compiler
        // just know what type you are thinking of ? 
It's to remove ambiguity that might be caused, when is "0" a signed number or unsigned number since it can be either.


It should be signed unless told otherwise (with a following u).
I think in that particular expression, the signedness of 0 is irrelevant. If it used any right shifts, that'd be a different story. For example, (int32_t)0x80000000 >> 1 == (int32_t)0xC0000000, but (uint32_t)0x80000000 >> 1 == (uint32_t)0x40000000.
Topic archived. No new replies allowed.