简体   繁体   English

“(无符号)值”是否投射未定义的行为?

[英]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 . unsignedunsigned int相同。

The cast will convert the signed integer to unsigned as follows:强制转换会将有符号整数转换为无符号整数,如下所示:

https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_conversions 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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