前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.100:不要混用有符号数和无符号数

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

作者头像
面向对象思考
发布2020-06-17 19:06:20
9320
发布2020-06-17 19:06:20
举报
文章被收录于专栏:C++核心准则原文翻译

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

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

Reason(原因)

Avoid wrong results.

避免错误的结果。

Example(示例)

代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-06-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档