Casting negative integer to larger unsigned integer

前端 未结 2 1549
悲&欢浪女
悲&欢浪女 2020-12-24 14:42

I\'ve encountered code that performs the following conversion:

static_cast(-1)

As far as I can tell, the C++ standard defin

2条回答
  •  星月不相逢
    2020-12-24 15:23

    From the C++11 standard, 4.7 "Integral conversions", para 2:

    If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type).

    In other words, when converting to an unsigned integer, only the value of the input matters, not its type. Converting -1 to an n-bit unsigned integer will always give you 2n-1, regardless of which integer type the -1 started as.

提交回复
热议问题