ES.102: Use signed types for arithmetic
ES.102:使用有符号数进行数学运算
Reason(原因)
Because most arithmetic is assumed to be signed; x - y yields a negative number when y > x except in the rare cases where you really want modulo arithmetic.
因为大部分数学运算都是有符号的。当x>y时,x-y会返回一个负数,极少情况实际需要的是按模运算。
Example(示例)
Unsigned arithmetic can yield surprising results if you are not expecting it. This is even more true for mixed signed and unsigned arithmetic.
如果不是你有意为之,无符号运算可能产生意外的结果。如果混用有符号数和无符号数,问题会更明显。
Here we have been very explicit about what's happening, but if you had seen us - (s + 2) or s += 2; ...; us - s, would you reliably have suspected that the result would print as 4294967294?
代码中我们已经很明确地知道发生了什么。但是如果你看到us - (s + 2) or s += 2; ...; us - s,你真的可以想象结果是4294967294么?
Exception(例外)
Use unsigned types if you really want modulo arithmetic - add comments as necessary noting the reliance on overflow behavior, as such code is going to be surprising for many programmers.
如果你真的需要按模运算-增加必要的注释提示对溢出行为的依赖,这样的代码会令很多程序员疑惑。
Example(示例)
The standard library uses unsigned types for subscripts. The built-in array uses signed types for subscripts. This makes surprises (and bugs) inevitable.
标准库使用无符号类型作为下标。内置数组使用有符号数作为下标。这会导致代码难于理解并不可避免地带来错误。
Use gsl::index for subscripts; see ES.107.
使用ES.107中介绍的gsl::index作为下标。
Enforcement(实施建议)
- Flag mixed signed and unsigned arithmetic
- 标记有符号数和无符号数混用的数学运算。
- Flag results of unsigned arithmetic assigned to or printed as signed.
- 标记将无符号数学运算的结果赋值给有符号数或者作为有符号数print输出的情况。
- Flag negative literals (e.g. -2) used as container subscripts.
- 标记使用负值作为容器下标的情况。
- (To avoid noise) Do not flag on a mixed signed/unsigned comparison where one of the arguments is sizeof or a call to container .size() and the other is ptrdiff_t.
- (为了避免误判)当一个参数是sizeof或者container.size()的返回值,而另一个参数是ptrdiff_t的时候,不要标记有符号数/无符号数混合的比较操作。
原文链接
https:///isocpp/CppCoreGuidelines/blob/master/#es102-use-signed-types-for-arithmetic
新书介绍
以下是本人3月份出版的新书,拜托多多关注!

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。
对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。
觉得本文有帮助?欢迎点赞并分享给更多的人。
阅读更多更新文章,请关注微信公众号【面向对象思考】
















