简体   繁体   中英

Is "(unsigned)value" cast undefined behaviour?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM