C++ 带符号和无符号之间隐式转换的代码安全性

2024-04-30

根据有符号整数类型和无符号整数类型之间隐式转换的规则,讨论here https://stackoverflow.com/questions/17832815/c-implicit-conversion-signed-unsigned and here https://stackoverflow.com/questions/50605/signed-to-unsigned-conversion-in-c-is-it-always-safe,当求和时unsigned int with a int, 签署的int首先被转换为unsigned int.

例如,考虑以下最小程序

#include <iostream>

int main()
{
   unsigned int n = 2;
   int x = -1;

   std::cout << n + x << std::endl;

   return 0;
}

尽管如此,该程序的输出仍如预期为 1:x首先被转换为unsigned int,以及与n导致整数溢出,给出“正确”的答案。

在类似于前一个代码的代码中,如果我确定n + x是正数,我可以假设unsigned int n and int x给出期望值?


在像上一个这样的代码中,如果我确定 n + x 是正数,我可以假设 unsigned int n 和 int x 的总和给出预期值吗?

Yes.

一、有符号值转换的 http://www.eel.is/c++draft/conv.integral#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).

那么两个无符号值将是added http://www.eel.is/c++draft/basic.fundamental#4使用模运算:

Unsigned integers shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.

这意味着您将得到预期的答案。

即使结果在数学意义上是负数,C++ 中的结果也将是一个模等于负数的数。

请注意,我在这里假设您添加两个相同大小的整数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ 带符号和无符号之间隐式转换的代码安全性 的相关文章

随机推荐