sta*_*usa 4 c++ unsigned modulus
我发现以下行为令人惊讶:
int a = -2; int b = 5; uint c = 5; std::cout << a%b << '\n'; std::cout << a%c << '\n'; Output: -2 4
当涉及比较时,混合有符号和无符号是有问题的 - 运算符中是否存在隐藏的比较%,或者此处是否还有其他事情发生?
%
Bat*_*eba 6
假设uint是一种unsigned类型没有窄比int,在表达的评价a % c,a被转换为uint和它将具有值-2 + std::numeric_limits<uint>::max() + 1.
uint
unsigned
int
a % c
a
-2 + std::numeric_limits<uint>::max() + 1
对于32位uint,该数字是4294967294,其中模5是4.
对于16位uint,该数字是65534,其中模5再次是4.
参考:https://en.cppreference.com/w/c/language/conversion
归档时间:
7 年,4 月 前
查看次数:
201 次
最近记录: