C++核心准则ES.100:不要混用有符号数和无符号数

2020-06-11 23:22

3f7a2ebaddd9465edfd794b1562aee0f.webp

ES.100: Don't mix signed and unsigned arithmetic

ES.100:不要混用有符号数和无符号数


Reason(原因)

Avoid wrong results.

避免错误的结果。


Example(示例)

int x = -3;
unsigned int y = 7;

cout << x - y << '\n'; // unsigned result, possibly 4294967286
cout << x + y << '\n'; // unsigned result: 4
cout << x * y << '\n'; // unsigned result, possibly 4294967275

It is harder to spot the problem in more realistic examples.

在更加贴近实际开发的代码中发现问题会更加困难。


Note(注意)

Unfortunately, C++ uses signed integers for array subscripts and the standard library uses unsigned integers for container subscripts. This precludes consistency. Use gsl::index for subscripts; see ES.107.

不幸的是,C++使用有符号整数作为数组的下标,而标注库使用无符号整数作为数组的小标,这破坏了一致性原则。使用gsl::index作为下标。参见ES.107。


Enforcement(实施建议)

  • Compilers already know and sometimes warn.

  • 编译器可以识别这方面的问题,有时会发出警告。

  • (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://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es87-dont-add-redundant--or--to-conditions




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!


浏览 148
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报