9

I know the u suffix means 'unsigned'. But is in necessary in the following code?

uint32_t hash = 2166136261u;

Is it a matter or convention? Or does it have any technical significance in this case? The value should be converted to unsigned anyway because uint32_t is unsigned.

When should I and when should I not use the u suffix for unsigned integer values?

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131

1 Answers1

5

No it is not necessary. Things get interesting at 2147483648 and your number is greater than this.

Note that formally 2166136261 is a long or a long long type if int has 32 bits or fewer. But either are convertible to a uint32_t in a well-defined way.

As a final point: the equivalent hex 0x811C9DC5 is an unsigned type if int has 32 bits or more. Oh joy!

Reference: https://en.cppreference.com/w/c/language/integer_constant

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 3
    I'll just leave it here: http://port70.net/~nsz/c/c11/n1570.html#6.4.4.1p5 – Eugene Sh. Apr 12 '19 at 16:32
  • @EugeneSh.: And we can add binary literals to the hex and octal case if C gets them. (C++ has from C++14). – Bathsheba Apr 12 '19 at 16:32
  • What if `int` is 16 bits long? – magras Apr 12 '19 at 16:33
  • @magras: I just wacked that in. It doesn't matter. `2166136261` would be a `long` or a `long long` if `long` is not long enough. I was longing to write that; now I don't need to wait any longer. – Bathsheba Apr 12 '19 at 16:34
  • @Bathsheba wouldn't the rules for binary constants depend on the implementation? As their very existence depends on it... – Eugene Sh. Apr 12 '19 at 16:44
  • @EugeneSh.: It might do, but see the corresponding C++ page to the link I posted: https://en.cppreference.com/w/cpp/language/integer_literal – Bathsheba Apr 12 '19 at 16:45
  • @EugeneSh. So it is not neccessarry since the first one fit in the table you link refers to will be taken. Right? – Some Name Apr 12 '19 at 16:47
  • 2
    @SomeName What is not necessary? Update: Ah, you mean the suffix. Yes, as the answer is stating. – Eugene Sh. Apr 12 '19 at 16:48