I am writing some code to test for a bit in a bit-field and I wrote this:
return (unsigned)(m_category | category) > 0
I though this wouldn't compile, since I didn't give the integer type, but to my surprise it did. So I'm wondering, what does this do? Is it undefined?
CodePudding user response:
unsigned
is the same as unsigned int
.
The cast will convert the signed integer to unsigned as follows:
https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_conversions
If the destination type is unsigned, the resulting value is the smallest unsigned value equal to the source value modulo 2n where n is the number of bits used to represent the destination type. That is, depending on whether the destination type is wider or narrower, signed integers are sign-extended[footnote 1] or truncated and unsigned integers are zero-extended or truncated respectively.