Strictly speaking, according to the C standard, are unsigned suffixes ever required for numeric literals in any Bitwise operation (to avoid UB)? Particularly around shifts, I think it is undefined behaviour when involving signed numbers and my understanding is that literals are signed but I am not sure. I.e.
4 << x; // or is 4U << x required?
4 >> x;
4 & x;
4 | x;
// etc. for all bit ops
x << 4;
x >> 4;
// etc.
where 4 is a placeholder for any literal.
I know that most compilers would not care either way, I am just interested in what the spec says.
1
No, unsigned
suffixed aren’t strictly required using bitwise operators, that’s because the ANSI C standard says at chapter 2.9 that bitwise operators must be applied to signed
or unsigned
integer operands (char
, short
, int
and long
).
However, especially in shifts, where the amount of bits to shift cannot be a negative number, would a bit more correct to specify it anyway.
Frithurik Grint is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
The C standard has no prohibition on using an integer literal (which the standard calls a “constant”) without an unsigned-suffix. However, getting the desired result may require a suffix.
Most simply, consider 1 << n
where n
is 31 and int
is 32 bits. Then 1 << n
is not defined by the C standard, because 231 is not representable in int
, but 1u << n
is defined.
1